【发布时间】:2020-12-29 19:52:21
【问题描述】:
有没有人尝试在 iOS 14 Widget 中更新用户的位置?
在阅读了 Apple 开发者论坛后,我提出了 CLLocationManager 的写作包装器并以这种方式使用它:
class WidgetLocationManager: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager? {
didSet {
self.locationManager!.delegate = self
}
}
private var handler: ((CLLocation) -> Void)?
func fetchLocation(handler: @escaping (CLLocation) -> Void) {
self.handler = handler
self.locationManager!.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.handler!(locations.last!)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
}
并以这种方式使用它:
var widgetLocationManager = WidgetLocationManager()
func getTimeline(for configuration: SelectPlaceIntent, in context: Context, completion: @escaping (Timeline<Entry>) -> Void) {
if widgetLocationManager.locationManager == nil {
widgetLocationManager.locationManager = CLLocationManager()
widgetLocationManager.locationManager!.requestWhenInUseAuthorization()
}
widgetLocationManager.fetchLocation(handler: { location in
print(location)
.......
})
}
我在 Widget 的 info.plist 中也有这两个条目:
<key>NSLocationUsageDescription</key>
<string>1</string>
<key>NSWidgetWantsLocation</key>
<true/>
当 locationManager.requestLocation() 被调用时,授权状态为 authorisedWhenInUse,但委托的方法永远不会被调用。我错过了什么?
【问题讨论】:
标签: ios swift core-location widgetkit