Search code examples
iosswiftswift3locationmanager

How do i do a background network call when i get the location?


When the location is changed in the background I want to update location to the server. I want a safe way to update location in the background every time I receive a significant location change. How do I make a network call?

 func endBackgroundUpdateTask() {
        UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
        self.backgroundUpdateTask = UIBackgroundTaskInvalid
    }


    func scheduledLocationManager(_ manager: APScheduledLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(locations.last?.description ?? "no location")
        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            Alamofire.request("https://testomkar.herokuapp.com/log", method: .post, parameters: ["log":locations.last?.description ?? "no location"]).validate().responseJSON(completionHandler: { (responce) in
                self.endBackgroundUpdateTask()
            })
        })


    }

Solution

  • If the application is in background state then get UIBackgroundTaskIdentifier

     func scheduledLocationManager(_ manager: APScheduledLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        print(locations.last?.description ?? "no location")
    
        // Get the background identifier if the app is in background mode
        if UIApplication.shared.applicationState == .background {
           backgroundUpdateTask = UIApplication.shared.beginBackgroundTask { [weak self] in
                if let strongSelf = self {
                    UIApplication.shared.endBackgroundTask(strongSelf.backgroundUpdateTask)
                    self.backgroundUpdateTask = UIBackgroundTaskInvalid
                }
            }
        }
    
        // Call the api to update the location to your server
        Alamofire.request("https://testomkar.herokuapp.com/log", method: .post, parameters: ["log":locations.last?.description ?? "no location"]).validate().responseJSON(completionHandler: { (responce) in
    
               //API completion block invalidate the identifier if it is not invalid already.
               if self.backgroundUpdateTask != nil && self.backgroundUpdateTask != UIBackgroundTaskInvalid {
                     UIApplication.shared.endBackgroundTask(backgroundUpdateTask)
                     self.backgroundUpdateTask = UIBackgroundTaskInvalid
               }
         })
    }