gpt4 book ai didi

ios - Swift:当应用程序在后台时调用 .requestLocation()

转载 作者:行者123 更新时间:2023-11-29 06:00:58 26 4
gpt4 key购买 nike

如果我在应用程序后台调用 .requestLocation(),则永远不会调用 locationManager didUpateLocations 方法。当应用程序打开时它会起作用。我已设置 .allowsBackgroundLocationUpdates = true 并且测试手机选择 .authorizedAlways 作为授权状态。 requestLocation 不能在后台工作吗?

为了澄清,我在 didReceiveRemoteNotification 委托(delegate)方法中调用它。每次我向设备发送远程推送通知时,如果应用程序在后台,我希望调用 .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 委托(delegate)方法。

调用completionHandler告诉iOS您已经完成后台处理。当您在 requestLocation 之后立即执行此操作时,iOS 会在调用位置委托(delegate)之前挂起您的应用。

您可以使用 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()
}
}

关于ios - Swift:当应用程序在后台时调用 .requestLocation(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54677300/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com