gpt4 book ai didi

ios - 获取位置后如何进行后台网络调用?

转载 作者:可可西里 更新时间:2023-11-01 01:18:55 27 4
gpt4 key购买 nike

当在后台更改位置时,我想将位置更新到服务器。每次收到重大位置更改时,我都希望有一种安全的方式在后台更新位置。如何调用网络电话?

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


}

最佳答案

如果应用程序处于后台状态,则获取 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
}
})
}

关于ios - 获取位置后如何进行后台网络调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844194/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com