【问题标题】:How can I find users location when app is in background or killed state?当应用程序处于后台或终止状态时,如何找到用户位置?
【发布时间】:2018-09-15 07:30:31
【问题描述】:

当我的应用程序处于后台或终止状态时,我想获得一个新位置。我搜索了很多并在Apple doc中找到了方法。 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")
        }
    }

【问题讨论】:

  • 您需要开启后台模式功能。
  • @ElTomato 我已经完成了。

标签: swift core-location cllocationmanager


【解决方案1】:

设置后台模式能力后,您可以使用 startMonitoringSignificantLocationChanges() 代替 startUpdatingLocations()。此方法会通知您 500 米的变化。

您可以通过公共 api 阅读此报价。

只要设备从之前的通知移动 500 米或更远,应用程序就会收到通知。它不应期望通知的频率超过每五分钟一次。如果设备能够从网络中检索数据,则位置管理器更有可能及时发送通知。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-27
    相关资源
    最近更新 更多