CLLocationManager 在ios8定位功能实现

1 导入框架 CoreLocation.framework

2 导入头文件 

#import <CoreLocation/CoreLocation.h>

3 遵守代理

<CLLocationManagerDelegate>

4 设置全局属性

@property (strong, nonatomic) CLLocationManager* locationManager;

5 viewdidload里面 

[self startLocation];

 1 //开始定位
 2 -(void)startLocation
 3 {
 4     self.locationManager = [[CLLocationManager alloc] init];
 5     self.locationManager.delegate = self;
 6     self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
 7     self.locationManager.distanceFilter = 10.0f;
 8     
 9     if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0)
10     {
11         //设置定位权限 仅ios8有意义
12         // [self.locationManager requestWhenInUseAuthorization];// 前台定位
13         
14           [self.locationManager requestAlwaysAuthorization];// 前后台同时定位
15     }
16     [self.locationManager startUpdatingLocation];
17 }

6 info.plist增加字段,(ios8 必须要)一般无法弹出获取定位权限的alert的原因就在这

   NSLocationWhenInUseUsageDescription   //允许在前台获取GPS的描述
   NSLocationAlwaysUsageDescription   //允许在前、后台获取GPS的描述 

此处设置必须和第5步的定位权限对应上,如果是前台定位,就在plist里面NSLocationWhenInUseUsageDescription

并不是 俩项都必须要加

效果图:

7 定位成功后的代理方法

 1 //定位代理经纬度回调
 2 -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
 3     
 4     [self.locationManager stopUpdatingLocation];
 5     //    NSLog(@"location ok");
 6     //
 7     //    NSLog(@"%@",[NSString stringWithFormat:@"经度:%3.5f\n纬度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);
 8     
 9     CLGeocoder * geoCoder = [[CLGeocoder alloc] init];
10     [geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
11         for (CLPlacemark * placemark in placemarks) {
12             
13             NSDictionary *test = [placemark addressDictionary];
14             //  Country(国家)  State(城市)  SubLocality(区)
15             self.title = [test objectForKey:@"City"];
16         }
17     }];
18     
19 }

定位失败的回调:

 1 /**
 2  *  1 定位失败的回调
 3  *  2 或者是用户点击了不允许定位的时候
 4  */
 5 - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
 6 {
 7     if ([error code] == kCLErrorDenied)
 8     {
 9         //访问被拒绝
10     }
11     if ([error code] == kCLErrorLocationUnknown) {
12         //无法获取位置信息
13     }
14 }

 

posted @ 2015-04-03 14:51  流觞若火  阅读(173)  评论(0编辑  收藏  举报