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,
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Varun Wadhwa
Varun is a mobile developer with experience in various technologies like Titanium , Cordova and native iOS development.