I'm having troubles getting CoreLocation
working in WidgetKit
. I was able to do so using an ObservableObject
class in a SwiftUI app just fine. Now I'm not sure how to do so with a widget.
I added LocationManager
to my TimelineEntry
and then called the requestLocation
function in getTimeline()
but it didn't work either. I'm not seeing any updates in my Widget. I added the proper keys to my widget as explained 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)
}
}