How to Use Core Location in iOS Swift

Posted By : Varun Wadhwa | 10-Apr-2017

In this blog I'll explain how to use core location in Swift 3.0.

Core location framework is use to obtain location related information of user.

The basic classes we are going to use are CLLocationManager and CLLocation.

Location Manager can be created by using following code :

var locationManager: CLLocationManager = CLLocationManager()

 

Before tracking location we've to request for permission from user  location manager instance can be used to request permissions depending upon requirement.

 

locationManager.requestWhenInUseAuthorization()

 

or

 

locationManager.requestAlwaysAuthorization()

 

 

Then we've to set the desired accuracy 

 

locationManager.desiredAccuracy = kCLLocationAccuracyBest  

 

 

To get updates on user location we've to conform to delegate  CLLocationManagerDelegate (and locationManager.delegate = self)

and the methods that must be implemented are : locationManager(_ manager: CLLocationManager,  didUpdateLocations locations: [CLLocation]) and locationManager(_ manager: CLLocationManager,  didFailWithError error: Error)

from didUpdateLocation method we can get CLLocation instances when there is change in location. and from this instance we can obtain useful information like latitude , longitude , speed and  altitude of user etc.


let location = locations[0]
print(location.cordinate.latitude) // prints user's latitude
print(location.cordinate.longitude) //will print user's longitude
print(location.speed) //will print user's speed

To start location update we must call startUpdatingLocation() on location manager 

 

locationManager.startUpdatingLocation()

 

 

Thanks,

About Author

Author Image
Varun Wadhwa

Varun is a mobile developer with experience in various technologies like Titanium , Cordova and native iOS development.

Request for Proposal

Name is required

Comment is required

Sending message..