Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request a user's location only once using requestLocation

I am trying to get user location only one time when app is opening first time. (Other openings I do not want to know it)

I do not want allow from user.

I am using below code but it did not tell me location and it gives me error like: The operation couldn’t be completed. (kCLErrorDomain error 0.)

PS: I am not using simulator I am trying with real device

Codes:

import CoreLocation
import UIKit

class ViewController: UIViewController, CLLocationManagerDelegate {
    let manager = CLLocationManager()

    override func viewDidLoad() {
        manager.delegate = self
        manager.requestLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            print("Found user's location: \(location)")
        }
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Failed to find user's location: \(error.localizedDescription)")
    }
}
like image 957
Jessica Avatar asked Sep 16 '26 08:09

Jessica


1 Answers

It is likely not working as you have to request the user's permission for their location, even if it is just the one time. I'm afraid there is no way around it and as it should be. It will only work if the user authorizes it.

You need this in the ViewDidLoad()

manager.requestWhenInUseAuthorization()

and the relevant Info.plist privacy key added:

Privacy - Location When In Use Usage Description

like image 132
Louis Leung Avatar answered Sep 18 '26 22:09

Louis Leung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!