蘋果在iOS8上更新了CoreLocation的受權獲取方式,在原來的基礎上,不只須要調用受權函數,還須要對info.plist進行相應的配置。app
在iOS上獲取經緯度使用的是CoreLocationManager,它來自CoreLocation.framework框架,使用時應當包含框架的總頭文件:框架
#import <CoreLocation/CoreLocation.h>
[self.manager requestAlwaysAuthorization]; [self.manager requestWhenInUseAuthorization];通常直接獲取第一個便可,應用面更廣。
除此以外,在info.plist中加入兩個鍵,值爲string,string中的內容就是請求受權時顯示的說明:函數
對應於兩種受權,有NSLocationWhenInUseUsageDescription和NSLocationAlwaysUsageDescription兩個鍵。ui
在每次開啓應用時,會調用一個代理方法來判斷受權狀態:經過這個方法判斷是否受權成功,若是成功則調用startUpdatingLocation來開始定位。this
// 受權狀態發生改變時調用 -(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{ /* typedef NS_ENUM(int, CLAuthorizationStatus) { // User has not yet made a choice with regards to this application kCLAuthorizationStatusNotDetermined = 0, // This application is not authorized to use location services. Due // to active restrictions on location services, the user cannot change // this status, and may not have personally denied authorization kCLAuthorizationStatusRestricted, // User has explicitly denied authorization for this application, or // location services are disabled in Settings. kCLAuthorizationStatusDenied, // User has granted authorization to use their location at any time, // including monitoring for regions, visits, or significant location changes. kCLAuthorizationStatusAuthorizedAlways NS_ENUM_AVAILABLE(NA, 8_0), // User has granted authorization to use their location only when your app // is visible to them (it will be made visible to them if you continue to // receive location updates while in the background). Authorization to use // launch APIs has not been granted. kCLAuthorizationStatusAuthorizedWhenInUse NS_ENUM_AVAILABLE(NA, 8_0), // This value is deprecated, but was equivalent to the new -Always value. kCLAuthorizationStatusAuthorized NS_ENUM_DEPRECATED(10_6, NA, 2_0, 8_0, "Use kCLAuthorizationStatusAuthorizedAlways") = kCLAuthorizationStatusAuthorizedAlways };*/ switch (status) { case kCLAuthorizationStatusAuthorizedAlways: NSLog(@"持續使用受權"); [self.manager startUpdatingLocation]; break; case kCLAuthorizationStatusAuthorizedWhenInUse: NSLog(@"使用中受權"); [self.manager startUpdatingLocation]; break; case kCLAuthorizationStatusDenied: NSLog(@"受權被拒絕"); break; case kCLAuthorizationStatusNotDetermined: NSLog(@"等待用戶受權"); break; default: break; } }
- (void)viewDidLoad { [super viewDidLoad]; // 1.建立CoreLocationManager CLLocationManager *manager = [[CLLocationManager alloc] init]; self.manager = manager; // 2.成爲其代理 self.manager.delegate = self; if ([[UIDevice currentDevice].systemVersion doubleValue] >= 8.0) { [self.manager requestAlwaysAuthorization]; }else{ // iOS8之前直接開始定位 [self.manager startUpdatingLocation]; } }
有關經緯度、方向、區域判斷等請見下節。spa