在 iOS8 中提示位置授权

prompting for location authorization in iOS8

我看过这个网站、苹果开发网站和无数 YouTube 视频上的其他类似问题,但我仍然无法弄清楚。 Xcode/iOS8.

中关于获取用户位置的信息似乎很少

我有一个地图视图可以正常工作,除了当我点击一个按钮来获取我的位置时,没有任何反应,我在日志中看到

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

我不明白我做错了什么。我对编程很陌生,我看到的所有信息对我来说都没有多大意义。

我在我的应用中使用了故事板,具体代码如下:

mapViewController.h

#import <UIKit/UIKit.h>
#import <MapKit/MapKit.h>
#import <CoreLocation/CoreLocation.h>
@interface mapViewController : UIViewController  {
MKMapView *mapview;
}
@property (nonatomic, retain) IBOutlet MKMapView *mapview;
-(IBAction)setMap:(id)sender;
-(IBAction)getCurrentLocation:(id)sender;
@property (nonatomic, retain) IBOutlet CLLocationManager *locationManager;
@end

mapViewController.m

#import "mapViewController.h"
@interface mapViewController ()
@end
@implementation mapViewController {
CLLocationManager *locationManager;
}
@synthesize mapview;
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.locationManager.delegate=self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.requestWhenInUseAuthorization;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(IBAction)setMap:(id)sender {
switch (((UISegmentedControl *) sender).selectedSegmentIndex) {
    case 0:
        mapview.mapType = MKMapTypeStandard;
        break;
    case 1:
        mapview.mapType = MKMapTypeSatellite;
        break;
    case 2:
        mapview.mapType = MKMapTypeHybrid;
        break;
       default:
        break;
}
}
-(IBAction)getCurrentLocation:(id)sender {
mapview.showsUserLocation = YES;
}
@end

我已经为此苦苦挣扎了很长时间,以至于我都快崩溃了。谁能指出我哪里出错了?

错误消息很容易解释。

首先,您没有在 viewDidLoad 中初始化 CLLocationManager。您可以使用(在 delegate 行之前)进行初始化:

self.locationManager = [[CLLocationManager alloc] init];

然后,您必须使用 [self.locationManager requestWhenInUseAuthorization][self.locationManager requestAlwaysAuthorization] 请求定位服务。 (不要忘记在 Info.plist 中添加相应的用法描述键)。

最后,您必须检查用户授权的响应。如果用户拒绝授权,您不应启动任何与位置服务相关的操作,直到您再次询问。


更新 如果你也支持iOS 7,代码会略有不同。