Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
import UIKit
import CoreLocation
class ViewController: UIViewController {
var locationManager: CLLocationManager
var userLocation: CLLocation?
init(locationProvider: CLLocationManager = CLLocationManager()) {
self.locationManager = locationProvider
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
}
func requestUserLocation() {
if CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
locationManager.startUpdatingLocation()
} else {
locationManager.requestWhenInUseAuthorization()
}
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
manager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations.last
manager.stopUpdatingLocation()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.