【发布时间】:2017-04-13 10:40:50
【问题描述】:
我正在制作一个使用设备定位服务的应用程序。每次位置发生变化时,该服务都需要捕获位置,并且它应该在所有情况下(背景/前景/终止)保持运行,所以我使用 startMonitoringSignificantLocationChanges() 方法,但是当我将它发送到后台,它可以工作一段时间然后停止,之后它不会捕获任何位置。我移动了文档建议的距离以获取位置更新(500m),但没有任何反应。我可能做错了什么?注意:在模拟器上可以完美运行,但是在物理设备上就不行了。
Info.plist 文件启用了后台设置
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>location</string>
</array>
AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if (launchOptions != nil) {
let locationManager = CLLocationManager()
locationManager.delegate = ViewController()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = CLActivityType.other
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startUpdatingLocation()
}
return true
}
func applicationDidEnterBackground(_ application: UIApplication) {
let locationManager = CLLocationManager()
locationManager.delegate = ViewController()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.activityType = CLActivityType.other
locationManager.allowsBackgroundLocationUpdates = true
locationManager.startMonitoringSignificantLocationChanges()
}
ViewController.swift
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Capture of new location
}
【问题讨论】:
-
您如何识别位置变化?您是否向自己发送任何本地通知?
-
didEnterBackground为时已晚,无法启用位置更新。如果你在那里这样做,你只会在有限的时间内收到更新。尝试在您的应用仍在前台时启用重要的位置更改设置。 -
@SivajeeBattina 在屏幕上打印位置变化时
-
实际检查情况如何。您是从 GPX 文件中更改位置还是要外出检查?
-
@SivajeeBattina 我要去外面看看
标签: ios swift3 location core-location background-fetch