我创建了一个应用程序 (Swift 4.0),当它接近 iBeacon 时,它会通过 startUpdatingLocation()
启动本地化。
一切都很完美,无论是在前台、后台还是被杀死的应用程序。
但有时该位置无法启动。
看起来它从未被调用过 locationManager(_ manager: CLLocationManager, didUpdateLocationslocations: [CLLocation])
我登录了所有内容:调用了 startUpdatingLocation
方法,并且所有内容都已正确配置。
我还尝试将 startMonitoringSignificantLocationChanges()
与 startUpdatingLocation()
结合使用:这样,本地化在可能由 调用的回调之后开始startMonitoringSignificantLocationChanges
(实际上超过500米后触发第一次检测)。但即使这个技巧也并不总是有效。
我还尝试了 allowDeferredLocationUpdates(untilTraveled distance: CLLocationDistance, timeout: TimeInterval)
来启动本地化,但什么也没有。
我还尝试异步启动本地化:它没有解决。
我尝试使用 pausesLocationUpdatesAutomatically
true 和 false:什么都没有。
永远不会调用 locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
方法。
下面是locationManager
配置代码和本地化激活方法:
func configureLocationService() {
locationManager = CLLocationManager()
locationManager?.delegate = AppDelegate.shared
locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager?.distanceFilter = Double(Configuration.getMinimumDistanceInMeters())
locationManager?.activityType = .fitness
locationManager?.pausesLocationUpdatesAutomatically = true
// locationManager?.pausesLocationUpdatesAutomatically = false
locationManager?.allowsBackgroundLocationUpdates = true
if #available(iOS 11.0, *) {
locationManager?.showsBackgroundLocationIndicator = true
} else {
// Fallback on earlier versions
}
locationManager?.requestAlwaysAuthorization()
}
...
func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {
if CLLocationManager.locationServicesEnabled() && CLLocationManager.authorizationStatus() == .authorizedAlways {
manager.startMonitoringSignificantLocationChanges()
DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
manager.stopMonitoringSignificantLocationChanges()
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
manager.startMonitoringSignificantLocationChanges()
manager.startUpdatingLocation()
UIApplication.shared.applicationIconBadgeNumber += 1
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
}
}
}
}
我做错了什么吗?有没有办法始终使用 startUpdatingLocation() 激活位置?
最佳答案
如果您的位置代码已经正常工作,那么问题出在其他地方。
导致问题的一种常见情况是在 View Controller 生命周期方法(例如 viewDidLoad
或 viewDidAppear
)中设置位置管理器。如果应用程序在后台启动(从冷启动,而不是从挂起状态),则其 View Controller 将永远不会显示,并且 View 生命周期方法(例如 viewDidAppear
)永远不会被调用。
要调试后台位置问题,请将您的应用程序设置为在某些点(应用程序委托(delegate)方法、 View Controller 生命周期方法、位置管理器委托(delegate)方法)发送本地通知,您可以实时查看发生的情况。
关于ios - 位置管理器 : sometimes startUpdatingLocation don't start,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55647588/