【问题标题】:how can i find users location when app is killed ?应用程序被杀死时如何找到用户位置?
【发布时间】:2017-05-20 23:34:00
【问题描述】:

我可以在应用程序运行时找到用户的当前位置。但是当应用程序被杀死时我找不到位置。如何找到位置?

这段代码给了我一个当前位置;

 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)")
}

【问题讨论】:

  • 当你的应用程序被杀死时,什么都做不了,对吧?

标签: ios swift3 location


【解决方案1】:

A highly recommended reading.

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

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

接下来,您应该将特定的 Background Mode location key 添加到您的 app bundle 的 plist 中。

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-10
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多