Use CLLocationManager
:
class ViewController: UIViewController, CLLocationManagerDelegate {
// You must hold a strong reference to the location manager so make it an instance property
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
// Check your app's authorization status
switch CLLocationManager.authorizationStatus() {
case .authorizedWhenInUse, .authorizedAlways:
// Authorized, start tracking location
self.startUpdatingLocation()
case .notDetermined:
// Not authorized, ask for permission. You can also replace this with
// locationManager.requestAlwaysAuthorization() if your app needs it
locationManager.requestWhenInUseAuthorization()
default:
print("permission denied")
break;
}
}
// MARK: -
func startUpdatingLocation() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse || status == .authorizedAlways {
self.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let lastLocation = locations.last else {
return
}
// now do what you want with the user's location
}
}
Remember to add NSLocationWhenInUseUsageDescription
or NSLocationAlwaysUsageDescription
to your Info.plist
to explain why you need to know the user's location. Also prepare for the case when the user does not give you permission to access the phone's location - you have to decide what part of your app can run with knowing the user's location.