IOS-didFailWithError: Error Domain=kCLErrorDomain Code=0. (kCLErrorDomain error 0.)”

IOS-didFailWithError: Error Domain=kCLErrorDomain Code=0. (kCLErrorDomain error 0.)”

我尝试获取用户当前位置的经度和纬度,我的代码很简单:

- (void)viewDidLoad {
    self.locationManager=[[CLLocationManager alloc]init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    [locationManager startUpdatingLocation];
}

-(void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation
{
    float latitude=newLocation.coordinate.latitude;
    float longitude=newLocation.coordinate.longitude;
    NSLog(@"%f",latitude);
    NSLog(@"%f",longitude);
    [locationManager stopUpdatingLocation];

}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 
{
    NSLog(@"didFailWithError: %@", error);
}

我总是从 didFailWithError 方法中得到这个错误:

didFailWithError: Error Domain=kCLErrorDomain Code=0 "The operation couldn’t be completed. (kCLErrorDomain error 0.)" 

我想, 您需要在项目

.plist 中添加以下权限

NSLocationWhenInUseUsageDescription 并且该值为 Application would like to use your location

第二个是,在您的代码中添加 [locationManager requestWhenInUseAuthorization]; 行。

this code in i added :

- (void)viewDidLoad {
    self.locationManager=[[CLLocationManager alloc]init];
    [locationManager setDelegate:self];
    [locationManager setDesiredAccuracy:kCLLocationAccuracyNearestTenMeters];
    [locationManager requestWhenInUseAuthorization];
    [locationManager startUpdatingLocation];

}