Swift:当app在后台时调用.requestLocation()

问题描述 投票:0回答:1

如果我在我的应用程序的背景中调用.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)
}
ios swift push-notification core-location cllocationmanager
1个回答
0
投票

你的问题是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()
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.