在我的(社交)webview应用程序中,了解用户何时积极使用该应用程序是非常重要的。因此,当用户将应用程序放在后台(例如按Home)时,我想向服务器发送一个信号,说明应用程序在后台。代码将被执行,但永远不会到达服务器。我不知道为什么,我怀疑iOS可能不允许后台进程中的dataTask,或者我是不是做错了要求更多的backgroundTime来执行我的代码?
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()
    }
}发布于 2020-07-20 12:41:53
我想我找到了答案,iOS做而不是喜欢在sceneDidEnterBackground中开始新的任务。相反,我应该在sceneWillResignActive上触发这个调用,在那里,它似乎工作得很好。
在这个答案中找到了一些解释:https://stackoverflow.com/a/61692625/3120213
https://stackoverflow.com/questions/62957545
复制相似问题