iOS8以前使用CoreLocation定位
1沮协、首先定義一個全局的變量用來記錄CLLocationManager對象抖拦,引入CoreLocation.framework使用#import@property (nonatomic, strong) CLLocationManager *locationManager;
2王浴、初始化CLLocationManager并開始定位
self.locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10;
[_locationManager startUpdatingLocation];
3嗡载、實現(xiàn)CLLocationManagerDelegate的代理方法
(1)獲取到位置數(shù)據(jù)惩琉,返回的是一個CLLocation的數(shù)組闷供,一般使用其中的一個
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
CLLocation *currLocation = [locations lastObject];
NSLog(@"經(jīng)度=%f 緯度=%f 高度=%f", currLocation.coordinate.latitude, currLocation.coordinate.longitude, currLocation.altitude);
}
(2)獲取用戶位置數(shù)據(jù)失敗的回調(diào)方法烟央,在此通知用戶
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
if ([error code] == kCLErrorDenied)
{
//訪問被拒絕
}
if ([error code] == kCLErrorLocationUnknown) {
//無法獲取位置信息
}
}
4报咳、在viewWillDisappear關(guān)閉定位
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[_locationManager stopUpdatingLocation];
}
iOS8中使用CoreLocation定位
1厅篓、在使用CoreLocation前需要調(diào)用如下函數(shù)【iOS8專用】:
iOS8對定位進行了一些修改掺逼,其中包括定位授權(quán)的方法茧彤,CLLocationManager增加了下面的兩個方法:
(1)始終允許訪問位置信息
- (void)requestAlwaysAuthorization;
(2)使用應(yīng)用程序期間允許訪問位置數(shù)據(jù)
- (void)requestWhenInUseAuthorization;
示例如下:
self.locationManager = [[CLLocationManager alloc]init];
_locationManager.delegate = self;
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
_locationManager.distanceFilter = 10;
[_locationManager requestAlwaysAuthorization];//添加這句
[_locationManager startUpdatingLocation];
2钦扭、在Info.plist文件中添加如下配置:
(1)NSLocationAlwaysUsageDescription
(2)NSLocationWhenInUseUsageDescription
這兩個鍵的值就是授權(quán)alert的描述体斩,示例配置如下[勾選Show Raw Keys/Values后進行添加]: