前言:手机定位功能每个APP都会用到,接下来我就为大家演示如何定位,不足之处还望指出。
第一步导入框架
第二步:我直接把我文件里的代码给拷贝下来了我就不说了(文件继承NSObject)
.h文件
#importtypedef void(^LoactionBlock)(NSString *lat, NSString *lon);
@interface DKLoactionManager : NSObject
//单利
+(instancetype)sharedManager;
-(void)getGPS:(LoactionBlock)block;
@end
.m文件
#import "DKLoactionManager.h"#import@interface DKLoactionManager ()@property(nonatomic,strong) CLLocationManager *locmanager;
@property(nonatomic,copy) LoactionBlock block;
@end
@implementation DKLoactionManager
//1.单利
+(instancetype)sharedManager{
static DKLoactionManager *_manager;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_manager = [[DKLoactionManager alloc]init];
});
return _manager;
}
//2.
-(instancetype)init{
self = [super init];
if (self) {
_locmanager = [[CLLocationManager alloc]init];
[_locmanager setDesiredAccuracy:kCLLocationAccuracyBest];//所需的精度设置为最好
_locmanager.distanceFilter = 100;//距离过滤
_locmanager.delegate = self;
if (![CLLocationManager locationServicesEnabled]) {
NSLog(@"开启定位服务");
} else {
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];//设置授权
if (status == kCLAuthorizationStatusNotDetermined) {//如果未确定授权状态
[_locmanager requestWhenInUseAuthorization];//请求用户授权
}
}
}
return self;
}
//用户愿意接受定位服务才会调用这个方法
- (void)locationManager:(CLLocationManager *)manager
didUpdateToLocation:(CLLocation *)newLocation
fromLocation:(CLLocation *)oldLocation{
CLLocationCoordinate2D coor = newLocation.coordinate;//coordinate坐标
NSLog(@"%@",@(coor.latitude));
NSLog(@"%@",@(coor.longitude));
}
-(void)getGPS:(LoactionBlock)block{
self.block = block;
[self.locmanager startUpdatingLocation];//开始定位位置
}
@end
第三步在info.plist文件里添加(有的朋友可能打不出来我在这里给大家写出了,把这段代码添加进去就行了:Privacy - Location When In Use Usage Description)
第四步:在APPdelegate文件里面调用一下(代码如下:假设你使用的是我上面的代码)
[[DKLoactionManager sharedManager] getGPS:^(NSString *lat, NSString *lon) {
}];
第五步:效果图
尾笔:祝福大家身体健康,工作顺利。