iOS开发 CoreLocation实现定位服务
听语音
- |
- 浏览:111
- |
- 更新:2016-06-08 18:39
- |
- 标签:IOS
方法/步骤
-
创建工程项目和视图控制器
1、创建一个Sing View Application工程项目;
2、为项目命名,生成工程文件。
-
为适配iOS8需要配置info.plist文件
添加2行:
NSLocationAlwaysUsageDescription 设为Boolean类型 = YES
NSLocationWhenInUseUsageDescription 设为Boolean类型 = YES
-
引入CoreLocation框架
包含头文件:#import <CoreLocation/CoreLocation.h>
引用代理:CLLocationManagerDelegate
声明定位管理器: CLLocationManager *locationManager;
-
初始化对象
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.distanceFilter = 1.0;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
if([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization]; // 永久授权
[self.locationManager requestWhenInUseAuthorization]; //使用中授权
}
-
实现定位代理更新位置成功回调
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"经度:%f", newLocation.coordinate.longitude);
NSLog(@"纬度:%f", newLocation.coordinate.latitude);
NSLog(@"速度:%f 米/秒", newLocation.speed);
CLGeocoder * geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSDictionary *locationInfo = [[NSDictionary alloc]init];
for (CLPlacemark * placemark in placemarks) {
locationInfo = [placemark addressDictionary];
}
NSLog(@"%@",locationInfo);
}];
}
-
定位代理失败回调
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(@"%@", error);
}
-
开启/停止位置更新
开启:[self.locationManager startUpdatingLocation];
停止:[self.locationManager stopUpdatingLocation];
在viewDidLoad方法里面开启定位更新服务。