1

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()
    }
}
Pvel
  • 670
  • 1
  • 5
  • 11
  • Why don't you use print statements and proxy(Charles) to check whether the request is actually being made. – PGDev Jul 17 '20 at 16:10
  • I am, I just removed them from the code above. The code is executed, except for the "got response" part. – Pvel Jul 17 '20 at 21:56
  • I had not yet used Charles before, but I don't think I'm seeing the request show up there. I see a request to my (test) server, but not to Client/Background so I think it's some other component sending a quick signal. To summarise, the sceneDidEnterBackground is called, the request created, but dataTask doesn't get executed as far as I can see. Any ideas? – Pvel Jul 20 '20 at 10:26
  • Just did another experiment, got Charles to work with HTTPS in iOS Simulator. There is indeed no request sent out. The "let task = " line is executed (since a print() the line above it shows up in logging), but the task itself is not. – Pvel Jul 20 '20 at 12:19

1 Answers1

1

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

Pvel
  • 670
  • 1
  • 5
  • 11