gpt4 book ai didi

Swift 杀死了应用程序在位置服务中获取数据?

转载 作者:可可西里 更新时间:2023-11-01 01:07:02 30 4
gpt4 key购买 nike

我想在应用终止时获取数据。但我认为如果应用程序被杀死,我将无法获取数据。

位置更新服务在应用程序终止时运行。我可以在位置服务中获取我的数据并更新本地数据库吗?

或者有什么方法可以在应用程序被杀死时获取数据?只是我想请求一些 api,从中获取数据并插入本地数据库。

最佳答案

是的,你可以。您设置了后台任务但时间有限。

这取决于设备电池

一定要在Capabilities中打开Location Updates

可以查看this用于后台任务

示例代码:

final class LocationManager: NSObject {
static let shared = LocationManager()

private var backgroundTask = UIBackgroundTaskIdentifier.invalid
private let manager = CLLocationManager()

func startMonitoring() {
manager.delegate = self
manager.allowsBackgroundLocationUpdates = true
manager.pausesLocationUpdatesAutomatically = false
manager.startMonitoringSignificantLocationChanges()
manager.requestAlwaysAuthorization()
}

}

extension LocationManager: CLLocationManagerDelegate {

func locationManager(_ manager: CLLocationManager, didStartMonitoringFor region: CLRegion) {
print("LocationManager didStartMonitoringFor")
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("LocationManager \(error)")
}

func locationManager(_ manager: CLLocationManager, monitoringDidFailFor region: CLRegion?, withError error: Error) {
print("LocationManager \(error)")
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
postLocation(location: locations.first)
}
}

extension LocationManager {

private func postLocation(location: CLLocation?) {
guard let location = location else { return }

if UIApplication.shared.applicationState == .background {

backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "locationTaskName", expirationHandler: {
UIApplication.shared.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskIdentifier.invalid
})

DispatchQueue.global(qos: .background).async {
self.postRequest(location: location) { [weak self] in
guard let self = self else { return }
UIApplication.shared.endBackgroundTask(self.backgroundTask)
self.backgroundTask = UIBackgroundTaskIdentifier.invalid
}
}
} else {
postRequest(location: location)
}

}

private func postRequest(location: CLLocation, completion: (() -> Void)? = nil) {
// TODO Request
//service.sendLocation
}

关于Swift 杀死了应用程序在位置服务中获取数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56988895/

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