Last active
December 7, 2018 11:50
-
-
Save Juanpe/c4b0af6ac096a608e8737aba45c5345c 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 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