我正在制作一个使用设备定位服务的应用程序。每次位置发生变化时,该服务都需要捕获位置,并且它应该在所有情况下(后台/前台/已终止)保持运行,所以我使用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
}