Search code examples
iosswiftwkwebviewbackground-task

URL request on sceneDidEnterBackground (iOS13)


In my (social) webview-app it's quite important to know when users are actively using the app. Therefore, when the user puts the app in the background (e.g. by pressing Home), I want to send a signal to the server that the app is in the background. The code is executed, but the server is never reached. I'm not sure why, I suspect iOS might not allow a dataTask in a background process, or am I doing something wrong asking for more backgroundTime to execute my code?

func sceneDidEnterBackground(_ scene: UIScene)
{
    DispatchQueue.global().async {
        self.identifier = UIApplication.shared.beginBackgroundTask(withName: "Going to background") {
            UIApplication.shared.endBackgroundTask(self.identifier)
            self.identifier = UIBackgroundTaskIdentifier.invalid
        }
        let baseUrl = Bundle.main.object(forInfoDictionaryKey: "Base URL") as! String
        let url = URL(string: "\(baseUrl)/Client/background")!
        var request = URLRequest(url: url)

        request.httpMethod = "GET"
        let cookie = self.settings.string(forKey: "cookie")
        request.setValue(cookie, forHTTPHeaderField: "cookie")

        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            print("got response \(response)")
        }
        task.resume()
    }
}

Solution

  • I think I found the answer to this, iOS does not like starting new tasks in sceneDidEnterBackground. Instead, I should trigger this call on sceneWillResignActive and there it does seem to work fine.

    Found some explanation in this answer: https://stackoverflow.com/a/61692625/3120213