如何在应用程序被杀时找到用户位置?

时间:2017-05-19 16:00:22

标签: ios swift3 location

我可以在应用运行时找到用户的当前位置。但是当应用程序被杀时我无法找到位置。我怎样才能找到位置?

此代码为我提供了当前位置;

 func determineMyCurrentLocation() {
    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()

    if CLLocationManager.locationServicesEnabled() {
        locationManager.startUpdatingLocation()
        locationManager.startUpdatingHeading()

    }
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let userLocation:CLLocation = locations[0] as CLLocation


    print("user latitude = \(userLocation.coordinate.latitude)")
    print("user longitude = \(userLocation.coordinate.longitude)")
    latitude = userLocation.coordinate.latitude
    longitude = userLocation.coordinate.longitude
    UserDefaults(suiteName: "group.com.ReelKapi")!.set(latitude, forKey:"latitude")
    UserDefaults(suiteName: "group.com.ReelKapi")!.set(longitude, forKey:"longitude")


}

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

2 个答案:

答案 0 :(得分:1)

A highly recommended reading

首先,应用的用户必须允许您的应用在后台监控位置。我看到您正在使用requestAlwaysAuthorization()请求该权限,因此该部分已涵盖。

此外,您必须将allowsBackgroundLocationUpdates设置为YES。

接下来,您应该向应用包的plist添加特定的Background Mode location key

完成所有设置后,在BG模式下,您的应用将能够从您的代码现在使用的标准位置服务中获取活动(startUpdatingLocation())。

如果您的应用被用户或iOS杀死,它将再次加载到后台以接收区域进入/退出事件,访问事件或重要位置更新。因此,如果您希望重新启动应用,则必须使用其中一种。

答案 1 :(得分:0)

当应用程序被杀时操作系统不允许运行任何代码,因此您不能获得任何更新,尽管您可以使用nsuserDefaults中以前保存的位置。仅当用户重新启动应用程序时,它才处于前台状态,您可以从位置管理器获取更新位置。

相关问题