How do I get the user’s location on iOS?

Asked on 07/31/2024

1 search

To get the user's location on iOS, you can use the CoreLocation framework. Here are the steps to do this:

  1. Request Authorization: Before accessing the user's location, you need to request authorization. This can be done using the CLLocationManager and methods like requestWhenInUseAuthorization or requestAlwaysAuthorization.

  2. Handle Authorization States: You need to handle different authorization states such as notDetermined, restricted, denied, authorizedWhenInUse, and authorizedAlways.

  3. Use CoreLocation APIs: Once you have the necessary authorization, you can use CoreLocation APIs to get location updates.

Here is a simplified example of how you can achieve this:

import CoreLocation

class LocationManager: NSObject, CLLocationManagerDelegate {
    private let locationManager = CLLocationManager()

    override init() {
        super.init()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    }

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

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        switch status {
        case .notDetermined:
            // Request authorization
            locationManager.requestWhenInUseAuthorization()
        case .restricted, .denied:
            // Handle denied state
            print("Location access denied")
        case .authorizedWhenInUse, .authorizedAlways:
            // Start updating location
            locationManager.startUpdatingLocation()
        @unknown default:
            break
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.last {
            print("Location: \(location.coordinate.latitude), \(location.coordinate.longitude)")
        }
    }
}

Relevant Sessions from WWDC

For more detailed information, you can refer to the session What’s new in location authorization.