我在让CoreLocation在WidgetKit中工作时遇到麻烦。我可以在SwiftUI应用程序中使用ObservableObject类来做到这一点。现在,我不确定如何使用小部件做到这一点。
我将LocationManager添加到我的TimelineEntry中,然后在getTimeline()中调用requestLocation函数,但它也不起作用。我在我的小工具中看不到任何更新。我向我的小部件添加了正确的密钥,如here所解释的。
import Foundation
import CoreLocation
import WidgetKit
class LocationManager: NSObject, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var location: CLLocation?
override init() {
super.init()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
WidgetCenter.shared.reloadAllTimelines()
}
func requestUpdate(_ completion: @escaping () -> Void) {
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
WidgetCenter.shared.reloadAllTimelines()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.last else { return }
self.location = location
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}


发布于 2021-04-12 15:55:52
将我的位置管理器移到TimelineProvider,并将变量添加到我的小部件TimelineEntry中。CoreLocation现在可以正确更新。

https://stackoverflow.com/questions/67038340
复制相似问题