IOS 8 基本定位实现
2015-10-15 20:03
471 查看
首先在项目中导入定位所需的库,Build Phases --> Link Binary With Libraries -->CoreLocation.framework
在Info.plist文件中加入字段NSLocationWhenInUseUsageDescription或者NSLocationAlwaysUsageDescription,前者是应用使用时可定位,后者是后台可定位,根据需要设置,并设置为YES
其次在AppDelegate.m中导入所需头文件,并且遵循定位协议
可以编写一个函数启动定位,并在didFinishLaunchingWithOptions中调用
实现定位协议方法didUpdateLocations和didFailWithError
最后,如果只需要经纬度怎不需要逆地址解析,如果需要城市名要注意获得的城市后面带有“市”,需根据需求自行处理。
在Info.plist文件中加入字段NSLocationWhenInUseUsageDescription或者NSLocationAlwaysUsageDescription,前者是应用使用时可定位,后者是后台可定位,根据需要设置,并设置为YES
其次在AppDelegate.m中导入所需头文件,并且遵循定位协议
#import <CoreLocation/CoreLocation.h> @interface AppDelegate ()<CLLocationManagerDelegate> @property (strong, nonatomic) CLLocationManager *locationManager; @end
可以编写一个函数启动定位,并在didFinishLaunchingWithOptions中调用
- (void)startingLocation { self.locationManager = [[CLLocationManager alloc] init]; self.locationManager.delegate = self; self.locationManager.desiredAccuracy = kCLLocationAccuracyBest; self.locationManager.distanceFilter = 10.0f; [self.locationManager requestWhenInUseAuthorization]; [self.locationManager startUpdatingLocation]; }
实现定位协议方法didUpdateLocations和didFailWithError
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations { // 如果需要多次定位则不要此句 [self.locationManager stopUpdatingLocation]; CLLocation *curLocation = [locations lastObject]; // 所在位置经纬度 NSString *latitude = [NSString stringWithFormat:@"%f", curLocation.coordinate.latitude]; NSString *longitude = [NSString stringWithFormat:@"%f", curLocation.coordinate.longitude]; // 根据经纬度获得当前城市名 CLGeocoder *geocoder = [[CLGeocoder alloc] init]; [geocoder reverseGeocodeLocation:curLocation completionHandler:^(NSArray *array, NSError *error) { if (array.count > 0) { CLPlacemark *placeMark = [array objectAtIndex:0]; NSString *city = placeMark.locality; // 直辖市可能需要通过以下判断获取 if (!city) { city = placeMark.administrativeArea; } LogBlue(@"定位城市:%@", city); }else if (error == nil && [array count] == 0) { LogRed(@"%@", @"无任何信息"); }else if (error != nil) { LogRed(@"%@", @"定位错误"); LogRed(@"%@", error); } }]; } - (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error { NSLog(@"%@", error); if ([error code] == kCLErrorDenied) { // 访问被拒绝 LogRed(@"访问被拒绝"); }else if ([error code] == kCLErrorLocationUnknown) { // 无法获取位置信息 LogRed(@"无法获取位置信息"); } }
最后,如果只需要经纬度怎不需要逆地址解析,如果需要城市名要注意获得的城市后面带有“市”,需根据需求自行处理。
相关文章推荐
- CSS浮动和定位学习笔记
- C#实现txt定位指定行完整实例
- Flex中怎么给表格中的滚动条定位避免刷新回到原处
- 一个JavaScript操作元素定位元素的实例
- js中的如何定位固定层的位置
- JS弹出层单纯的绝对定位居中示例代码
- JavaScript网页定位详解
- 微信企业号开发之微信考勤百度地图定位
- 在Android里完美实现基站和WIFI定位
- android 定位的4种方式介绍
- Android判断服务是否运行及定位问题实例分析
- 高德地图(定位、描点)
- [IOS地图开发系类]1、CLLocationManager 位置定位
- 基于Visual Graph快速开发井下人员定位系统
- 关于调用百度和高德APP
- ***免杀方法
- Excel打印不了图片
- IE6/IE7下position:absolute;绝对定位偏移、不显示问题
- iOS 5:了解定位服务
- iOS 5:了解定位服务