Reputation: 165
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)")
}
}
Upvotes: 3
Views: 3680
Reputation: 3804
I figured out why. You need to call request authorization first and awhile before requesting location. If you do not ask for authorization, you get the kCLErrorDomain error 0. If you ask for authorization right before manager.requestLocation, your locationManager delegate methods would not be called at all. You can use when you need user's location:
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestLocation]; // Second time and beyond, didChangeAuthorizationStatus will not be called.
then in the call back you can request location from locationManager.
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
if (status == kCLAuthorizationStatusDenied) {
// The user denied authorization
}
else if (status == kCLAuthorizationStatusAuthorizedWhenInUse) {
[self.locationManager requestLocation];
}
}
Upvotes: 0
Reputation: 508
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
Upvotes: 3