Getting User's Location

in 5 simple steps

MORE TUTORIALS

Pre-Requisites

Import CoreLocation framework

import CoreLocation

Step 1 of 5

Inherit delegate class

class ViewController: UIViewController, CLLocationManagerDelegate {

Step 2 of 5

Initialize location manager

var locationManager : CLLocationManager!

override func viewDidLoad() {
   super.viewDidLoad()
   // Do any additional setup after loading the view, typically from a nib.

   locationManager = CLLocationManager()
   locationManager.delegate = self
   locationManager.desiredAccuracy = kCLLocationAccuracyBest
   locationManager.requestAlwaysAuthorization()

   if(CLLocationManager.locationServicesEnabled()){
     locationManager.startUpdatingLocation()
   }
}

Step 3 of 5

Implement delegate methods

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
   let userLocation:CLLocation = locations[0] as CLLocation
   manager.stopUpdatingLocation()
   print("Latitude: \(userLocation.coordinate.latitude)")
   print("Longtitude: \(userLocation.coordinate.longitude)")
}

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
  print(error)
}

Step 4 of 5

Run and test

Step 5 of 5