How to read the user's location using LocationButton
How to read the user's location using LocationButton êŽë š
Updated for Xcode 15
New in iOS 15
SwiftUI has a dedicated LocationButton
view for displaying a standard UI for requesting user location. Sadly, it doesnât do any of the work of getting the location for us, but it at least has a recognizable user interface that we can work with.
In order to use this, you first need to import two frameworks, one for reading the location and one for showing the button:
import CoreLocation
import CoreLocationUI
Next, you create some kind of ObservableObject
that is able to request the userâs location on demand. This needs to create a CLLocationManager
and call its requestLocation()
method on demand. You can then put that inside a SwiftUI view showing a location button.
So, you might write something like this:
class LocationManager: NSObject, ObservableObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
@Published var location: CLLocationCoordinate2D?
override init() {
super.init()
manager.delegate = self
}
func requestLocation() {
manager.requestLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
location = locations.first?.coordinate
}
}
struct ContentView: View {
@StateObject var locationManager = LocationManager()
var body: some View {
VStack {
if let location = locationManager.location {
Text("Your location: \(location.latitude), \(location.longitude)")
}
LocationButton {
locationManager.requestLocation()
}
.frame(height: 44)
.padding()
}
}
}
Apple provides a handful of variant designs for the button, activated by passing one of them in with its initializer â try LocationButton(.shareMyCurrentLocation)
, for example.