How to request user location?

Generated on 7/31/2024

1 search

To request user location in your app, you can use the CoreLocation framework. Here are the steps to do this, based on the information from the WWDC session "What’s new in location authorization":

  1. Request Authorization:

    • Use the CLLocationManager to request location authorization. You can request either "when in use" or "always" authorization.
    • For example, to request "when in use" authorization, you can use:
      let locationManager = CLLocationManager()
      locationManager.requestWhenInUseAuthorization()
      
  2. Handle Different Authorization States:

    • Users can grant different levels of location access, such as full accuracy or approximate location. You can request temporary full accuracy if needed:
      locationManager.requestTemporaryFullAccuracyAuthorization(withPurposeKey: "YourPurposeKey")
      
  3. Check Authorization Status:

    • You can check the current authorization status using the authorizationStatus property of CLLocationManager:
      let status = CLLocationManager.authorizationStatus()
      switch status {
      case .notDetermined:
          // Request authorization
      case .restricted, .denied:
          // Handle denied access
      case .authorizedWhenInUse, .authorizedAlways:
          // Access granted
      @unknown default:
          // Handle other cases
      }
      
  4. Use CL Service Sessions:

    • The new CLServiceSession provides a declarative way to manage location authorization. It helps to define your authorization goals and handle the session lifecycle:
      let serviceSession = CLServiceSession()
      serviceSession.requestAuthorization()
      

For more detailed information, you can refer to the session What’s new in location authorization at the timestamp 00:57.

Relevant Sessions