2017-06-30 2 views
2

Lorsque l'emplacement est modifié en arrière-plan, je souhaite mettre à jour l'emplacement sur le serveur. Je veux un moyen sûr de mettre à jour l'emplacement en arrière-plan chaque fois que je reçois un changement de lieu significatif. Comment faire un appel réseau?Comment faire un appel réseau en arrière-plan lorsque j'obtiens l'emplacement?

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() 
      }) 
     }) 


    } 

Répondre

2

Si l'application est dans un état d'arrière-plan, puis obtenir 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 
      } 
    }) 
}