Trying to get current location with using swiftUI. Below code, couldn't initialize with didUpdateLocations delegate.
class GetLocation : BindableObject {
var didChange = PassthroughSubject<GetLocation,Never>()
var location : CLLocation {
didSet {
didChange.send(self)
}
}
init() {}
}
As of Xcode 11 beta 4, you will need to change
didChange
towillChange
:This code below works (Not production ready). Implementing the
CLLocationManagerDelegate
works fine and thelastKnownLocation
is updated accordingly.Don't forget to set the
NSLocationWhenInUseUsageDescription
in yourInfo.plist
I have written a one-file swift package with usage instructions on https://github.com/himbeles/LocationProvider. It provides a
ObservableObject
-type wrapper class for CLLocationManager and its delegate. There is a published propertylocation
which can directly be used in SwiftUI, as well as a PassthroughSubject that you can subscribe to via Combine. Both update on everydidUpdateLocations
event of the CLLocationManager.It also handles the case where location access has previously been denied: The default behavior is to present the user with a request to enable access in the app settings and a link to go there.
In SwiftUI, use as