swift - 当应用程序处于后台或终止状态时,如何找到用户位置?

标签 swift core-location cllocationmanager

当我的应用程序处于后台或终止状态时,我想获取新位置。我查了很多资料,在苹果文档中找到了方法。 startMonitoringSignificantLocationChanges() 用于在应用处于后台或终止状态时更新位置。但是当我尝试这种方法时,没有获得处于杀死状态的位置。 这是我的代码:

override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
        locationManager.requestAlwaysAuthorization()
        locationManager.startMonitoringSignificantLocationChanges()
    }

//MARK: LOCATION MANAGER:
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let long :CLLocationDegrees = manager.location?.coordinate.longitude ?? 00.00000
        let lat :CLLocationDegrees = manager.location?.coordinate.latitude ?? 00.00000
        print(lat)
        print(long)
        let location = LocationTracking()
        location.latitude = lat
        location.longitude = long

        try! realm.write {
            realm.add(location, update: false)
        }
    }

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

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if (status == CLAuthorizationStatus.denied) {
            print("Location access denied")
        }
    }

最佳答案

打开后台模式功能后,您可以使用 startMonitoringSignificantLocationChanges() 而不是 startUpdatingLocations()。此方法会通知您 500 米内的变化。

您可以通过公共(public) API 阅读此引用。

Apps can expect a notification as soon as the device moves 500 meters or more from its previous notification. It should not expect notifications more frequently than once every five minutes. If the device is able to retrieve data from the network, the location manager is much more likely to deliver notifications in a timely manner.

https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati

关于swift - 当应用程序处于后台或终止状态时,如何找到用户位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52342634/

相关文章:

ios - Alamofire 4 网络流关闭

ios - 升级到 El-Capitan 后 Swift 编译器错误

ios - 如何使用 Swift iOS 将字符串中的每个单词大写

swift - swift 中存储的值类型对象在哪里?

ios - 核心位置不请求用户许可

ios - 我的 xamarin.ios 项目中的 CLLocation 为 Null

ios - 检测 iPhone 中的 GPS 硬件

ios - 在 CLLocationCoordinate2d 的半径内过滤 PHAssetCollection

ios - 如何在屏幕关闭时检测 iOS 应用程序中的 iBeacon?

ios - 当用户在应用程序启动区域时,Swift 4 locationManager didEnterRegion 不会触发