最近在做定位功能,只需要获取当前位置信息,包括经纬度、位置等,不需要持续获取。

对CoreLocation的封装。将定位相关的代码从 Controller 中分离,封装到 NSObject 对象中。采用 代理方法 降低代码的分散度,方便调用亦易于获取位置信息。

1,初始化

//初始化
- (instancetype)init {if (self = [super init]) {//创建CLLocationManager对象_locationManager = [[CLLocationManager alloc] init];_locationManager.desiredAccuracy = kCLLocationAccuracyBest;_locationManager.distanceFilter = 10.0;_locationManager.delegate = self;//请求用户授权if ([_locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {//当用户使用的时候授权[_locationManager requestWhenInUseAuthorization];}}return self;
}

2,代理方法

#pragma mark - CLLocationManagerDelegate
/**location.coordinate:坐标,包含经纬度location.altitude:设备海拔高度单位是米location.course:设置前进方向location.horizontalAccuracy:水平精准度location.verticalAccuracy:垂直精准度location.timestamp:定位信息返回的时间location.speed:设备移动速度单位是米/秒,适用于行车速度而不太适用于不行*/- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{//结束,防止重发定位//如果只需要获取一次,可以获取到位置之后就停止[self.locationManager stopUpdatingLocation];if (self.locationTimes != 0) return;//拿到最新的locationCLLocation *currentLocation = [locations lastObject];//反编码CLGeocoder * geoCoder = [[CLGeocoder alloc] init];[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {if (placemarks.count > 0) {//将字典转为模型NSDictionary *dic = [self getInfoWithPlacemark:placemarks[0]];LocationModel *model = [[LocationModel alloc]init];[model setValuesForKeysWithDictionary:dic];//首次判断代理是否存在,并在代理能够响应代理方法时才执行代理方法if (self.ldelegate && [self.ldelegate respondsToSelector:@selector(doSomethingAfterGetCityInformation:)]) {[self.ldelegate doSomethingAfterGetCityInformation:model];}}else if (error == nil && placemarks.count == 0) {NSLog(@"No location and error return");}else if (error) {NSLog(@"location error: %@ ",error);}}];self.locationTimes ++;
}
/**
授权状态
*/
- (void)locationManager:(CLLocationManager*)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{if(status ==kCLAuthorizationStatusNotDetermined) {NSLog(@"等待用户授权");}else if(status ==kCLAuthorizationStatusAuthorizedAlways||status ==kCLAuthorizationStatusAuthorizedWhenInUse){NSLog(@"授权成功");//开始定位[self.locationManager startUpdatingLocation];}else{NSLog(@"授权失败");}
}
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{NSLog(@"E:%@",error);if ([error code] == kCLErrorDenied) {NSLog(@"错误:拒绝定位");}else if ([error code] == kCLErrorLocationUnknown) {NSLog(@"错误:无法获取定位");}else {NSLog(@"%@",error.localizedDescription);}
}

3,整理位置信息

#pragma mark - 整理位置信息
- (NSDictionary *)getInfoWithPlacemark:(CLPlacemark *)placemark {// 经纬度CLLocationCoordinate2D coordinate = placemark.location.coordinate;NSString *longitude = [NSString stringWithFormat:@"%f",coordinate.longitude];NSString *latitude = [NSString stringWithFormat:@"%f",coordinate.latitude];// 省/市/县(区)/街道/详细地址NSString *province = placemark.administrativeArea;NSString *locality = placemark.locality;province = province ? province : placemark.locality;//若省不存在则为直辖市NSString *subCity = placemark.subLocality;NSString *street = placemark.addressDictionary[@"Street"];
//    NSString *name = placemark.name;NSString *address;if ([province isEqualToString:locality]) {address = [NSString stringWithFormat:@"%@%@%@",locality,subCity,street];}else {address = [NSString stringWithFormat:@"%@%@%@%@",province,locality,subCity,street];}NSDictionary *dic = @{@"longitude"  :longitude,@"latitude"   :latitude,@"province"   :province,@"locality"   :locality,@"subLocality":subCity,@"street"     :street,@"address"    :address};return dic;
}

4,使用

#import "ACCoreLocationViewController.h"
#import <CoreLocation/CoreLocation.h>
@interface ACCoreLocationViewController ()<CLLocationManagerDelegate>
@property (nonatomic,strong) CLLocationManager *locationManager;
@end@implementation ACCoreLocationViewController- (void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];[self.locationObject start];
}- (void)viewWillDisappear:(BOOL)animated{[super viewWillDisappear:animated];[self.locationObject end];
}- (void)viewDidLoad {[super viewDidLoad];// Do any additional setup after loading the view.self.locationObject = [[ACCoreLocationObject alloc]init];      _locationObject.ldelegate = self;
}/**
代理方法
*/
-(void)doSomethingAfterGetCityInformation:(LocationModel *)model{NSLog(@"城市%@",model.locality);
}

注意:

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations;

这个方法每隔一段时间就会调用一次,所以如果只需要定位一次的话,要做相应的处理。

  • 只获取一次定位
[self.locationManager requestLocation];
  • 一直持续获取定位
[self.locationManager startUpdatingLocation];

参考文章

CoreLocation定位封装

IOS 定位 CoreLocation的封装

iOS:CoreLocation实现定位当前城市

IOS位置和地图 CoreLocation框架

CoreLocation(地理定位)的基本使用

iOS开发-用户定位获取-CoreLocation的实际应用

iOS开发 --- 定位功能(系统框架CoreLocation)相关推荐

  1. Android Swift iOS开发:语言与框架对比

    转载自:http://www.infoq.com/cn/articles/from-android-to-swift-ios?utm_campaign=rightbar_v2&utm_sour ...

  2. 【iOS开发】从Cocoa框架说开去--Fundation框架系列

    [Cocoa简介] Cocoa是苹果公司为Mac OS X所创建的原生面向对象API 是Mac OS X上五大API之一.(其他四个:Carbon POSIX X11 Java)它是苹果的面向对象开发 ...

  3. iOS开发常用第三方开源框架

    iOS开发-常用第三方开源框架倾情整理!简书:https://www.jianshu.com/p/29cb22b13d79 iOS第三方库大全:https://blog.csdn.net/kanggu ...

  4. iOS开发 常用第三方开源框架

    iOS开发-常用第三方开源框架介绍(你了解的ios只是冰山一角) 2015-04-05 15:25 2482人阅读 评论(1) 收藏 举报 开源框架 图像: 1.图片浏览控件MWPhotoBrowse ...

  5. IOS开发之常用第三方框架(完善中)

    IOS开发之常用第三方框架 AFNetworking:网络请求 SDWebImage:加载网络图片 MJRefresh:下拉刷新 MBProgressHUD/SVProgressHUD:加载提示框 M ...

  6. iOS 开发之调用系统铃声以及震动

    iOS 开发之调用系统铃声以及震动 @interface AlarmClass : NSObject {SystemSoundID soundID; }//调用震动 -(void)systemShak ...

  7. ios开发 架子鼓功能开发_适用于iOS开发人员的功能标志

    ios开发 架子鼓功能开发 When building modern applications, things tend to move quite quickly. When you add mul ...

  8. Android与Swift iOS开发:语言与框架对比

    Swift是现在Apple主推的语言,2014年新推出的语言,比 Scala等"新"语言还要年轻10岁.2015年秋已经开源.目前在linux上可用,最近已经支持Android N ...

  9. iOS开发——定位 获取经纬度

    最近公司提供了一个学习iOS的机会,问我是否愿意学习iOS,还是继续只做android开发.我感觉非常幸运,能有此机会去学习iOS,当即说要学习iOS开发. 学习了几天啦,做了一个小demo实现了获取 ...

最新文章

  1. pg_basebackup 配置 stream replication 异步/同步
  2. java不同工厂生产不同电器_完整案例分析再加知识整合——艾特抽象工厂模式,超详细的...
  3. [Contest20171109]函数(lipshitz)
  4. 有线路由器与无线路由器混合使用
  5. 模板引擎——Thymeleaf
  6. 基数字符串排序c语言,基数排序(C语言)
  7. CHECKLIST TO USE BEFORE SUBMITTING A PAPER TO A JOURNAL
  8. Vue 学习 第六天学习笔记
  9. 实战渗透-Shiro反序列化漏洞实例
  10. 机器学习(三十四)——策略梯度
  11. java 类调用情况_java 如何调用类?情况如下
  12. 启动列表的activity
  13. 一文读懂NoSQL的模式 | 时光机
  14. 马克·扎克伯格分享Facebook水冷数据中心照片
  15. php处理post序列化,使用jQuery POST和php序列化和提交表单
  16. Go基础-go的源码文件以及常用命令
  17. Java核心类库之(常用API、字符串类、集合类、泛型)
  18. 连续两次入围Gartner魔力象限的Quick BI到底有何魔力?
  19. datadog ebpf模块 offset-guess.o 问题排查解决
  20. 正态分布 密度函数与分布函数

热门文章

  1. GAN系列之动漫风格迁移AnimeGAN2
  2. uva 1265 (LA 4848)
  3. text-shadow属性
  4. 解决Coursera视频打不开、访问速度慢等问题
  5. 项目生命周期及其主要工作
  6. win10系统运行vc6.0编译后的程序报:“0xc000007b应用程序无法正常启动”的解决方法
  7. U3D Input类之键位输入GetKey
  8. LidarMultiNet:在单个多任务网络中统一LiDAR语义分割、三维目标检测和全景分割
  9. 最完整的Springboot后台开发框架
  10. Flutter (Material) - Scaffold