Skip to content

Instantly share code, notes, and snippets.

@dimitris-c
Last active July 5, 2017 16:43
Show Gist options
  • Save dimitris-c/45cc5f640fc45e0ece3ec9329df948f4 to your computer and use it in GitHub Desktop.
Save dimitris-c/45cc5f640fc45e0ece3ec9329df948f4 to your computer and use it in GitHub Desktop.
import CoreLocation
enum LocationAuthorizationStatus {
case always
case whenInUse
}
final class LocationManager: NSObject, CLLocationManagerDelegate {
typealias LocationAuthorizationCompletion = (CLAuthorizationStatus) -> Void
typealias LocationRequestCompletion = (CLLocation?) -> Void
typealias LocationUpdatesBlock = (CLLocation?) -> Void
static let shared: LocationManager = LocationManager()
final fileprivate var statusCompletion: LocationAuthorizationCompletion?
final fileprivate var locationRequestCompletion: LocationRequestCompletion?
final let manager: CLLocationManager = CLLocationManager()
final var locationUpdates: LocationUpdatesBlock?
private override init() {
super.init()
self.setupCommon()
}
final fileprivate func setupCommon() {
self.manager.delegate = self
}
final func request(withAuthorizationStatus status: LocationAuthorizationStatus, and completion: @escaping LocationAuthorizationCompletion) {
self.statusCompletion = completion
switch status {
case .always:
self.manager.requestAlwaysAuthorization()
break
case .whenInUse:
self.manager.requestWhenInUseAuthorization()
break
}
}
final func startUpdatingLocation() {
self.manager.startUpdatingLocation()
}
final func stopUpdatingLocation() {
self.manager.stopUpdatingLocation()
}
final func requestCurrentLocation(with completion: @escaping LocationRequestCompletion) {
self.locationRequestCompletion = completion
self.manager.startUpdatingLocation()
}
final func startMonitoringSignificantLocationChanges() {
self.manager.startMonitoringSignificantLocationChanges()
}
final func stopMonitoringSignificantLocationChanges() {
self.manager.stopMonitoringSignificantLocationChanges()
}
// MARK: CLLocationManagerDelegate Methods
final func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
self.statusCompletion?(status)
}
final func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lastLocation = locations.last {
if self.locationRequestCompletion != nil {
self.stopUpdatingLocation()
self.locationRequestCompletion?(lastLocation)
self.locationRequestCompletion = nil
}
self.userLocation.value = lastLocation
self.locationUpdates?(lastLocation)
}
}
final func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if self.locationRequestCompletion != nil {
self.stopUpdatingLocation()
self.locationRequestCompletion?(nil)
self.locationRequestCompletion = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment