Determine User’s Current Location Example in Swift

In this tutorial, you will learn how to read user current location(latitude and longitude) and also how to listen for location updates continuously.

If you are interested in video lessons on how to write Unit tests and UI tests to test your Swift mobile app, check out this page: Unit Testing Swift Mobile App

Configure Info.plist

To make your iOS app be able to read the user current location, it needs to prompt a user for permission to do so. The user will see an alert dialog with a request and the question displayed in this Alert dialog needs to be provided in the info.plist of your app.

Unless you configure your Info.plist with the following properties, you will be seeing a similar error message in the Xcode console.

UserCurrentLocation[1567:128637] This app has attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain both “NSLocationAlwaysAndWhenInUseUsageDescription” and “NSLocationWhenInUseUsageDescription” keys with string values explaining to the user how the app uses this data

Open Info.plist file and add the following two properties.

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Will you allow this app to always know your location?</string>

<key>NSLocationWhenInUseUsageDescription</key>
<string>Do you allow this app to know your current location?</string>

After you add the above two properties into info.plist of your project and open it as a Property List, it will look like on the picture below.

Info.plist Permission Request

 

Allow to Access Location Permission

To prompt the user for permission to read their location updates you will need to create an instance of CLLocationManager class and call either requestAlwaysAuthorization() or requestWhenInUseAuthorization() function.

locationManager = CLLocationManager()
locationManager?.desiredAccuracy = kCLLocationAccuracyBest
locationManager?.requestWhenInUseAuthorization()

The Alert dialog that appears will look similar to the one below.

Allow Access Location Permission

If the user allows your app to access their current location, your app can read user’s latitude and longitude.

Check If User Granted Permission to Access Location

Your app can check if the user did grant their permission to access location details by calling a locationServicesEnabled() function on the CLLocationManager class.

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

Read User Location and Location Updates

To start receiving user location updates your controller class will need to conform to a CLLocationManagerDelegate protocol.

extension ViewController: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation
        
        // Call stopUpdatingLocation() to stop listening for location updates,
        // other wise this function will be called every time when user location changes.
        
        // manager.stopUpdatingLocation()
        
        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Error \(error)")
    }
}

Stop Receiving Location Updates

To stop receiving location updates, call the stopUpdatingLocation() function on CLLocationManager object.

locationManager.stopUpdatingLocation()

Complete Swift Code Example

Below is a complete code example you can copy into your project, run and see how to works. Do not forget to update the Info.plist as it is suggested at the beginning of this tutorial.

import UIKit
import CoreLocation

class ViewController : UIViewController {
    
    var locationManager: CLLocationManager?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        determineMyCurrentLocation()
    }
    
    func determineMyCurrentLocation() {
        locationManager = CLLocationManager()
        locationManager?.delegate = self
        locationManager?.desiredAccuracy = kCLLocationAccuracyBest
        locationManager?.requestAlwaysAuthorization()
        
        if CLLocationManager.locationServicesEnabled() {
            locationManager?.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }
}

extension ViewController: CLLocationManagerDelegate {
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation
        
        // Call stopUpdatingLocation() to stop listening for location updates,
        // other wise this function will be called every time when user location changes.
        
        // manager.stopUpdatingLocation()
        
        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
    {
        print("Error \(error)")
    }
}
 

Current location permission dialog disappears too quickly?

If the permission dialog disappears too quickly, then make you that you declare an object of CLLocationManager at the class level and initialize it at the method level. Notice in the code example above that I have declared an object of CLLocationManager outside of the method where it is initialized?

I hope this tutorial was of some help to you. Before you go, have a look around this web site for other Swift tutorials.  There are other very useful Swift tutorials you might find.

Happy Swift coding! 🙋🏻‍♂️

Leave a Reply

Your email address will not be published. Required fields are marked *

Free Video Lessons

Enter your email and stay on top of things,

Subscribe!