当在后台更改位置时,我想将位置更新到服务器。每次收到重大位置更改时,我都希望有一种安全的方式来更新后台位置。如何拨打网络电话?
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()
})
})
}
答案 0 :(得分:2)
如果应用程序处于后台状态,则获取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
}
})
}