How to get Current Location in iOS using Swift?

Get user's current location in iOS Swift



To get a user's current location in iOS Swift you need to declare:

let locationManager = CLLocationManager()

In viewDidLoad() you have to instanitate the CLLocationManager class, like this:

// Ask for Authorisation from the User.

self.locationManager.requestAlwaysAuthorization()

// For use in foreground

self.locationManager.requestWhenInUseAuthorization()

if CLLocationManager.locationServicesEnabled() {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
}

Then in CLLocationManagerDelegate method you can get user's current location coordinates:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    var locValue:CLLocationCoordinate2D = manager.location.coordinate
    print("locations = \(locValue.latitude) \(locValue.longitude)")
}

In the info.plist you will have to add NSLocationAlwaysUsageDescription and your custom alert message like, AppName(Demo App) would like to use your current location.


Video tutorial for getting Current Location in iOS using Swift?
 

Comments

Popular posts from this blog

Top 16 Mobile App Development Companies in India | App Developers 2017

CCEE CDAC Exam Questions

Important JavaScript Question Answers