Updated for Xcode 14.2
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.
SPONSORED Thorough mobile testing hasn’t been efficient testing. With Waldo Sessions, it can be! Test early, test often, test directly in your browser and share the replay with your team.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.