iOS8之前使用CoreLocation定位一、首先定義一個全局的變量用來記錄CLLocationManager對象,引入CoreLocation.framework使用#import <CoreLocation/CoreLocation.h>1 @property (nonatomic, strong) CLLocationManager *locationManager; 二、初始化CLLocationManager並開始定位 -(CLLocationManager *)locationManager{ #warning 定位服務不可用,直接返回空 if (![CLLocationManager locationServicesEnabled]) return nil; if (!_locationManager) { //建立定位者 self.locationManager = [[CLLocationManager alloc]init]; //設置代理 self.locationManager.delegate = self; } return _locationManager;}- (void)viewDidLoad {[super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; self.locationManager.distanceFilter = 10; [self.locationManager startUpdatingLocation];} 三、實現CLLocationManagerDelegate的代理方法(1)獲取到位置數據,返回的是一個CLLocation的數組,通常使用其中的一個 - (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{ CLLocation *currLocation = [locations lastObject]; NSLog(@"經度=%f 緯度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);} (2)獲取用戶位置數據失敗的回調方法,在此通知用戶- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{ if ([error code] == kCLErrorDenied) { //訪問被拒絕 } if ([error code] == kCLErrorLocationUnknown) { //沒法獲取位置信息 }} 四、在viewWillDisappear關閉定位 - (void)viewWillDisappear:(BOOL)animated{ [super viewWillDisappear:animated]; [_locationManager stopUpdatingLocation];} iOS8中使用CoreLocation定位一、在使用CoreLocation前須要調用以下函數【iOS8專用】:iOS8對定位進行了一些修改,其中包括定位受權的方法,CLLocationManager增長了下面的兩個方法:(1)始終容許訪問位置信息- (void)requestAlwaysAuthorization;(2)使用應用程序期間容許訪問位置數據- (void)requestWhenInUseAuthorization;示例以下: - (void)viewDidLoad {[super viewDidLoad]; self.view.backgroundColor = [UIColor whiteColor]; self.locMgr.desiredAccuracy = kCLLocationAccuracyBest; self.locMgr.distanceFilter = 10; #warning 定位服務,ios8之後添加這句 [self.locMgr requestAlwaysAuthorization]; [self.locMgr startUpdatingLocation];} 二、在Info.plist文件中添加以下配置:(1)NSLocationAlwaysUsageDescription(2)NSLocationWhenInUseUsageDescription