目标C中的位置授权问题

时间:2016-05-31 15:19:16

标签: objective-c authorization mkmapview userlocation

我有一个问题,显示目标C中的用户位置。 我尝试了在stackoverflow中找到的所有东西,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.

谢谢:)

2 个答案:

答案 0 :(得分:0)

请看以下几行

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

错误表明您刚刚启动了位置更新,而没有提示进行位置授权。

在提示进行位置授权之前,您将启动位置更新。所以这些行的顺序是错误的。

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

2)然后开始更新位置

因此,您的代码应遵循以下顺序。

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

//2
[locationManager startUpdatingLocation];

不要忘记在Info.plist中添加NSLocationAlwaysUsageDescription或NSLocationWhenInUseUsageDescription键

答案 1 :(得分:0)

我不能将此作为评论发布,因此我会在此处发布。

您只需在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是一个本地方法变量。它应该声明为实例变量或属性。