在 iOS 7 以及更早之前的版本,MapView 顯示使用者位置不需實作到 CLLocationManager ,現在都要了。
在 iOS 8 上編譯會出現以下 log :
Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.
首先必須要修改 info.plist
新增 key值為 NSLocationWhenInUseUsageDescription 或 NSLocationAlwaysUsageDescription
Value值為要出現在螢幕上的字,終於可以客製化訊息了!但也可以留白。
兩者差異僅在前者只有使用中才會定位,後者是在背景也會持續定位。
接著修改程式碼,第5行是重點
locationManager = [[CLLocationManager alloc] init]; locationManager.delegate = self; locationManager.desiredAccuracy=kCLLocationAccuracyBest; if([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) { [locationManager requestWhenInUseAuthorization]; } [locationManager startUpdatingLocation];
另外授權檢查部分也要修改,請注意4,5行的差異
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status { if ( ([locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)] && status != kCLAuthorizationStatusNotDetermined && status != kCLAuthorizationStatusAuthorizedWhenInUse) || (![locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)] && status != kCLAuthorizationStatusNotDetermined && status != kCLAuthorizationStatusAuthorized) ) { NSString *message = @"您的手機目前並未開啟定位服務,如欲開啟定位服務,請至設定->隱私->定位服務,開啟本程式的定位服務功能"; UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"無法定位" message:message delegate:nil cancelButtonTitle:@"確定" otherButtonTitles: nil]; [alertView show]; }else { [locationManager startUpdatingLocation]; } }
上面那行是 iOS 8 以上,第二行是 iOS 7 以下,因為 kCLAuthorizationStatusAuthorized 在 iOS 8 完全不能使用。
別的地方要這樣寫
CLAuthorizationStatus status = [CLLocationManager authorizationStatus]; if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status == kCLAuthorizationStatusAuthorized) { // 開始定位 }else { // 顯示警告 }