Determine User’s Current Location Example in Swift

In this Swift code example, you will learn how to determine user’s current location using CLLocationManager and CLLocationManagerDelegate. The code example below will cover:

  • Request user’s permission for your app to always be able to read user’s location. Optionality you could use requestWhenInUseAuthorization() instead of requestAlwaysAuthorization(),
  • Update projects Info.plist with String values for NSLocationAlwaysUsageDescription and NSLocationWhenInUseUsageDescription alert dialogs,
  • Implement locationManager didUpdateLocations function to continuously listen for location updates and call stopUpdatingLocation() to stop listening for location updates,
  • Get user’s current location latitude and longitude.

The Info.plist

For your app to be able to request user’s current location, you will need to open Info.plist file as Source Code and add two new keys and corresponding values like for example I did:

<key>NSLocationAlwaysUsageDescription</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>

Determine User’s Current Location. Complete Example in Swift

import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
    
    var locationManager:CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        determineMyCurrentLocation()
    }
    
    
    func determineMyCurrentLocation() {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        
        if CLLocationManager.locationServicesEnabled() {
            locationManager.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        }
    }
    
    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)")
    }
}

For more Swift code examples and tutorials, please check the Swift Code Examples page on this website.


Leave a Reply

Your email address will not be published.