迅速杀死的应用程序在位置服务中获取数据?

时间:2019-07-11 12:11:38

标签: swift swift3

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

应用终止后,位置更新服务正在运行。我可以在定位服务中获取数据并更新本地数据库吗?

或者在应用被杀死时以任何方式获取数据?我只是想请求一些api,从中获取数据并插入本地数据库。

2 个答案:

答案 0 :(得分:2)

可以。您设置了background task但时间有限。

取决于设备电池

确保在Location Updates中打开Capabilities

您可以检查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
    }

答案 1 :(得分:1)

可悲,但 。由于您的应用已关闭,因此您无法获取任何数据或进行任何其他操作。当应用程序打开并进行一些数学运算时,您可以执行所有操作。