如果我在我的应用程序的背景中调用.requestLocation()
,则永远不会调用locationManager didUpateLocations
方法。它在应用程序打开时有效。我已经设置.allowsBackgroundLocationUpdates = true
和测试手机选择.authorizedAlways
授权状态。 requestLocation
不在后台工作吗?
为了澄清,我在didReceiveRemoteNotification
委托方法中调用它。每当我向设备发送远程推送通知时,我希望在后台应用程序时调用.requestLocation()
。这不可能吗?
didReceiveRemoteNotification
:
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if CLLocationManager.authorizationStatus() == .authorizedAlways {
locationManager.requestLocation()
}
completionHandler(UIBackgroundFetchResult.newData)
}
你的问题是requestLocation
将异步完成;可能需要一些时间来确定用户的位置并调用didUpdateLocations
委托方法。
调用completionHandler
告诉iOS你已完成后台处理。正如您在requestLocation
iOS在调用位置委托之前暂停您的应用程序之后立即执行此操作。
您可以使用DispatchGroup
确定何时检索到该位置并准备好暂停:
class AppDelegate: UIApplicationDelegate, CLLocationManagerDelegate {
var backgroundDispatchGroup: DispatchGroup?
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if CLLocationManager.authorizationStatus() == .authorizedAlways {
self.backgroundDispatchGroup = DispatchGroup()
self.backgroundDispatchGroup?.enter()
locationManager.requestLocation()
self.backgroundDispatchGroup?.notify {
completionHandler(UIBackgroundFetchResult.newData)
self.backgroundDispatchGroup = nil
}
} else {
completionHandler(UIBackgroundFetchResult.noData)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// Do whatever with the location
self.backgroundDispatchGroup?.leave()
}
}