Skip to content

Instantly share code, notes, and snippets.

@Juanpe
Last active December 7, 2018 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Juanpe/c4b0af6ac096a608e8737aba45c5345c to your computer and use it in GitHub Desktop.
Save Juanpe/c4b0af6ac096a608e8737aba45c5345c to your computer and use it in GitHub Desktop.
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