Objective C 中的位置授权问题

Location authorization issue in Objective C

我在显示 objective C 中的用户位置时遇到问题。 我尝试了我在 Whosebug 中可以找到的所有内容,aaaand,没有用。

所以我有那个代码:

-(void)setLocation
{
    CLLocationManager *locationManager = [[CLLocationManager alloc] init];
    MKPointAnnotation *myAnnotation = [[MKPointAnnotation alloc]init];


    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
    locationManager.distanceFilter = 10.0;
    [locationManager startUpdatingLocation];
    [locationManager requestWhenInUseAuthorization];
    [locationManager requestAlwaysAuthorization];



    myAnnotation.coordinate = mapView.userLocation.location.coordinate;

    myAnnotation.title = @"Test";
    myAnnotation.subtitle = @"I am a test Subtitle";

    [self.mapView addAnnotation:myAnnotation];
}

-(void)mapView:(MKMapView *)mapView didUpdateUserLocation:(MKUserLocation *)userLocation {
    [self.mapView setCenterCoordinate:userLocation.coordinate animated:YES];
}

一切都在 ViewController.m 中,更准确地说是在我的 .h 文件中声明的 mapView 中:

@property (strong, nonatomic) IBOutlet MKMapView *mapView;

有人知道吗?我的错误是:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

谢谢:)

看下面几行

[locationManager startUpdatingLocation];
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];

一条错误提示您刚刚开始位置更新,但没有提示位置授权。

您在提示位置授权之前开始位置更新。所以这些行的顺序是错误的。

1) 提示用户进行位置更新

2) 然后开始更新位置

因此您的代码应按以下顺序排列。

//1
[locationManager requestWhenInUseAuthorization];
[locationManager requestAlwaysAuthorization];

//2
[locationManager startUpdatingLocation];

不要忘记在 Info.plist

中添加 NSLocationAlwaysUsageDescription 或 NSLocationWhenInUseUsageDescription 键

我无法post将其作为评论,所以我将post放在这里。

您只需在 TextEdit 中打开 Info.plist 文件并添加这些行即可。

<key>UIBackgroundModes</key>
<array>
    <string>location</string>
    <string>external-accessory</string>
    <string>remote-notification</string>
</array>
<key>NSLocationUsageDescription</key>
<string>App needs to use GPS to keep track of your activity</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>App needs to use GPS to keep track of your activity</string>
<key>UIRequiredDeviceCapabilities</key>
<array>
    <string>armv7</string>
    <string>gps</string>
</array>

编辑:

我看到你的 locationManager 是一个本地方法变量。它应该声明为实例变量或 属性.