Skip to content

Instantly share code, notes, and snippets.

@andresr-dev
Created April 28, 2022 17:05
Show Gist options
  • Select an option

  • Save andresr-dev/4c7ab478e31975e90ceb73f724b304d9 to your computer and use it in GitHub Desktop.

Select an option

Save andresr-dev/4c7ab478e31975e90ceb73f724b304d9 to your computer and use it in GitHub Desktop.
This is a class that helps you get the current location of the user and below there's an example of how to use it. IMPORTANT: You must provide a description in target/info/"Privacy - Location When In Use Usage Description"
import CoreLocation
class LocationFetcher: NSObject, CLLocationManagerDelegate {
let manager = CLLocationManager()
var location: ((CLLocation) -> Void)?
var authorizationChanged: ((Bool) -> Void)?
override init() {
super.init()
self.manager.delegate = self
}
func start() {
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lastKnownLocation = locations.first {
location?(lastKnownLocation)
manager.stopUpdatingLocation()
print("user location: \(lastKnownLocation)")
}
}
func isAuthorized() -> Bool {
if manager.authorizationStatus == .authorizedWhenInUse || manager.authorizationStatus == .authorizedAlways {
return true
} else {
return false
}
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
if manager.authorizationStatus == .authorizedWhenInUse || manager.authorizationStatus == .authorizedAlways {
authorizationChanged?(true)
} else {
authorizationChanged?(false)
}
}
}
import SwiftUI
import CoreLocation
struct LocationFetcherExample: View {
let locationFetcher = LocationFetcher()
@State private var locationAuthorized = false
@State private var placemark: CLPlacemark?
var body: some View {
VStack(spacing: 20) {
if locationAuthorized {
Text("Current Location")
.font(.title.weight(.semibold))
Label(
placemark == nil ? "Fetching Location…" : "\(placemark!.locality ?? ""), \(placemark!.country ?? "")",
systemImage: "mappin.and.ellipse"
)
} else {
Text("😞 Location not authorized!")
Button("Open Settings") {
openSettings()
}
}
}
.onAppear(perform: getCurrentLocation)
}
private func getCurrentLocation() {
locationFetcher.location = {
updatePlacemark(location: $0)
}
locationFetcher.authorizationChanged = { authorized in
locationAuthorized = authorized
}
locationAuthorized = locationFetcher.isAuthorized()
locationFetcher.start()
}
private func updatePlacemark(location: CLLocation) {
CLGeocoder().reverseGeocodeLocation(location) { placemarks, _ in
if let placemark = placemarks?.first {
self.placemark = placemark
}
}
}
private func openSettings() {
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
UIApplication.shared.open(settingsUrl) { success in
print("Settings opened: \(success)")
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment