Created
May 5, 2023 08:13
-
-
Save cedricbahirwe/2248416eb8362fe6b379d2a7f9dd3c55 to your computer and use it in GitHub Desktop.
A simple class illustration the use of CoreLocation to get ask and access user's location in SwiftUI
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import CoreLocation | |
{ | |
private let locationManager = CLLocationManager() | |
@Published var authorisationStatus: CLAuthorizationStatus = .notDetermined | |
@Published private(set) var userLocation: UserLocation? | |
private let merchantProvider: MerchantProtocol | |
var permissionStatus: LocationStatus { | |
switch authorisationStatus { | |
case .authorizedAlways, .authorizedWhenInUse: return .granted | |
default: return .denied | |
} | |
} | |
init(_ merchantProvider: MerchantProtocol = FirebaseManager()) { | |
self.merchantProvider = merchantProvider | |
super.init() | |
self.locationManager.delegate = self | |
} | |
private func getLastKnownLocation() -> UserLocation? { | |
DialerStorage.shared.getLastKnownLocation() | |
} | |
public func requestAuthorisation(always: Bool = false) async { | |
if always { | |
do { | |
try await locationManager.requestTemporaryFullAccuracyAuthorization(withPurposeKey: "") | |
} catch { | |
authorisationStatus = .notDetermined | |
} | |
} else { | |
locationManager.requestWhenInUseAuthorization() | |
} | |
} | |
func getLatestLocation() -> UserLocation? { | |
guard permissionStatus == .granted, | |
let location = locationManager.location | |
else { return getLastKnownLocation() } | |
return UserLocation(location.coordinate) | |
} | |
enum LocationStatus: String, Codable { | |
case granted | |
case denied | |
} | |
} | |
extension LocationManager: CLLocationManagerDelegate { | |
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) { | |
let newAuthorizationStatus = manager.authorizationStatus | |
// let accuracy = manager.accuracyAuthorization | |
DispatchQueue.main.async { | |
self.authorisationStatus = newAuthorizationStatus | |
if newAuthorizationStatus == .authorizedWhenInUse || newAuthorizationStatus == .authorizedAlways { | |
manager.startUpdatingLocation() | |
} | |
} | |
} | |
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
DispatchQueue.main.async { | |
guard let lastLocation = locations.last else { return } | |
self.userLocation = UserLocation(lastLocation.coordinate) | |
try? DialerStorage.shared.saveLastKnownLocation(self.userLocation!) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment