You will create a simple application which shows how far you are from Chester
milesLabel
In order to use location services within iOS, permission must be granted by the user, to do this developers must set a configuration option in the Info.plist file containing a message to the end user explaining why access is required
Open the Info.plist file and click the + sign which appears when you hover the mouse over the words Information Property List at the topimport CoreLocation
CLLocationManager
: var locationManager = CLLocationManager()
viewDidLoad
method, we need to check the authorisation status for location services, which will be one of the following:
If it is NotDetermined, then the user has not been asked to allow location monitoring, and we are permitted to prompt them to request access. If it is denied, then we would need to inform the user to allow access in Settings (we cannot prompt again for permission, but we may instead instruct them how to change settings). If the status is Restricted then the user does not have permission to allow access (for example parental controls are enabled), and locations services cannot be enabled. Finally, if we have either of the Authorized statuses then we can start to use location services, furthermore, if the status is AuthorizedAlways, we would be able to carry out location tasks in the background.
Add the following code to request authorisation when the app is in use:if CLLocationManager.authorizationStatus() == .notDetermined {
locationManager.requestWhenInUseAuthorization()
}
We now need to configure the location manager object to monitor location - the first thing to do is to set how accurate the location needs to be - the more accurate the location the higher the power consumption, so we should typically choose the lowest acceptable level of accuracy that meets our requirements. Note that BestForNavigation provides a higher level of accuracy then 'Best' but is intended to be user when the device is plugged in (for example when used for in car navigation)
Add the following code, beneath the if statement, to set the location accuracy to the nearest 100 metreslocationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.delegate = self
class ViewController: UIViewController, CLLocationManagerDelegate {
locationManager.startUpdatingLocation()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//get the most recent location
let lastLocation = locations.last!
//create a location object with the coordinates for Chester
let chester = CLLocation(latitude: 53.191824, longitude: -2.891015)
//calculate the distance from Chester
let distanceInMetres = lastLocation.distance(from: chester)
let distanceInMiles = distanceInMetres / 1609.34
milesLabel.text = String(format: "%.1f", distanceInMiles)
}