0

我在目标 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.

谢谢 :)

4

2 回答 2

0

我不能将此作为评论发布,所以我将其发布在这里。

您可以简单地Info.plist在 TextEdit 中打开文件并添加这些行。

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

于 2016-06-01T08:14:43.310 回答
0

看下面几行

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

错误提示您刚刚开始位置更新而没有提示位置授权。

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

1) 提示用户更新位置

2)然后开始更新位置

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

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

//2
[locationManager startUpdatingLocation];

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

于 2016-05-31T16:14:37.213 回答