Last active
September 21, 2020 05:24
-
-
Save olivaresf/48a884aac986d279a8ff9f67138cb607 to your computer and use it in GitHub Desktop.
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 Foundation | |
import CoreLocation | |
class Location: NSObject { | |
static let shared = Location() | |
private override init() { | |
super.init() | |
manager.delegate = self | |
} | |
var lastLocation: CLLocation? | |
// This is really weird o.O | |
var didMove = [(CLLocation) -> Void]() | |
func onMove(_ block: @escaping (CLLocation) -> Void) { | |
didMove.append(block) | |
} | |
private let manager = CLLocationManager() | |
} | |
// MARK: - LocationManager | |
extension Location { | |
enum AuthState { | |
case allowed | |
case denied | |
case undetermined | |
init(status: CLAuthorizationStatus) { | |
switch status { | |
case .authorizedAlways, | |
.authorizedWhenInUse: | |
self = .allowed | |
case .denied, | |
.restricted: | |
self = .denied | |
case .notDetermined: | |
self = .undetermined | |
} | |
} | |
} | |
var authorization: AuthState { | |
return AuthState(status: CLLocationManager.authorizationStatus()) | |
} | |
var currentLocation: CLLocation? { | |
return manager.location | |
} | |
func requestAuthorization() { | |
manager.requestWhenInUseAuthorization() | |
} | |
func beginUpdates() { | |
manager.startUpdatingLocation() | |
} | |
func endUpdates() { | |
manager.stopUpdatingLocation() | |
} | |
} | |
extension Location: CLLocationManagerDelegate { | |
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
guard let currentLocation = locations.last else { return } | |
guard let lastLocation = lastLocation else { self.lastLocation = currentLocation; return } | |
let distance = currentLocation.distance(from: lastLocation) | |
if distance > 100 { | |
self.lastLocation = currentLocation | |
didMove.forEach { $0(currentLocation) } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment