iOS 获取经纬度

废话不多说,直接上代码。

添加权限

首先要在plist文件里添加两个键值对,向用户请求位置服务时会显示在这里设置的值的内容。

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

头文件内容

#import <Foundation/Foundation.h>
#import <CoreLocation/CoreLocation.h>

typedef void(^MoLocationSuccess) (double lat, double lng);
typedef void(^MoLocationFailed) (NSError *error);

@interface MoLocationManager : NSObject<CLLocationManagerDelegate>
{
    CLLocationManager *manager;
    MoLocationSuccess successCallBack;
    MoLocationFailed failedCallBack;
}

+ (MoLocationManager *) sharedGpsManager;

+ (void) getMoLocationWithSuccess:(MoLocationSuccess)success Failure:(MoLocationFailed)failure;

+ (void) stop;


@end

实现文件内容

#import "MoLocationManager.h"
#import <UIKit/UIKit.h>

@implementation MoLocationManager

+ (MoLocationManager *) sharedGpsManager {
    static MoLocationManager *shared = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shared = [[MoLocationManager alloc] init];
    });
    return shared;
}

- (id)init {
    self = [super init];
    if (self) {
        // 打开定位 然后得到数据
        manager = [[CLLocationManager alloc] init];
        manager.delegate = self;
        //控制定位精度,越高耗电量越
        manager.desiredAccuracy = kCLLocationAccuracyBest;
        
        // 兼容iOS8.0版本
        /* Info.plist里面加上2项
         NSLocationAlwaysUsageDescription      Boolean YES
         NSLocationWhenInUseUsageDescription   Boolean YES
         */
        
        // 请求授权 requestWhenInUseAuthorization用在>=iOS8.0上
        // respondsToSelector: 前面manager是否有后面requestWhenInUseAuthorization方法
        // 1. 适配 动态适配
        if ([manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [manager requestWhenInUseAuthorization];
            [manager requestAlwaysAuthorization];
        }
        // 2. 另外一种适配 systemVersion 有可能是 8.1.1
        float osVersion = [[[UIDevice currentDevice] systemVersion] floatValue];
        if (osVersion >= 8) {
            [manager requestWhenInUseAuthorization];
            [manager requestAlwaysAuthorization];
        }
    }
    return self;
}

- (void) getMoLocationWithSuccess:(MoLocationSuccess)success Failure:(MoLocationFailed)failure {
    successCallBack = [success copy];
    failedCallBack = [failure copy];
    // 停止上一次的
    [manager stopUpdatingLocation];
    // 开始新的数据定位
    [manager startUpdatingLocation];
}


+ (void) getMoLocationWithSuccess:(MoLocationSuccess)success Failure:(MoLocationFailed)failure {
    [[MoLocationManager sharedGpsManager] getMoLocationWithSuccess:success Failure:failure];
}


- (void) stop {
    [manager stopUpdatingLocation];
}

+ (void) stop {
    [[MoLocationManager sharedGpsManager] stop];
}

// 每隔一段时间就会调用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
    for (CLLocation *loc in locations) {
        CLLocationCoordinate2D l = loc.coordinate;
        double lat = l.latitude;
        double lnt = l.longitude;
        
        successCallBack ? successCallBack(lat, lnt) : nil;
    }
}

//失败代理方法
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    failedCallBack ? failedCallBack(error) : nil;
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}

@end

客户端调用

    //只获取一次
    __block  BOOL isOnece = YES;
    [MoLocationManager getMoLocationWithSuccess:^(double lat, double lng){
        isOnece = NO;
        //只打印一次经纬度
        NSLog(@"lat lng (%f, %f)", lat, lng);
        
        if (!isOnece) {
            [MoLocationManager stop];
        }
    } Failure:^(NSError *error){
        isOnece = NO;
        NSLog(@"error = %@", error);
        if (!isOnece) {
            [MoLocationManager stop];
        }
    }];
    
    
//    //一直持续获取定位则
//    [MoLocationManager getMoLocationWithSuccess:^(double lat, double lng){
//        //不断的打印经纬度
//        NSLog(@"lat lng (%f, %f)", lat, lng);
//    } Failure:^(NSError *error){
//        NSLog(@"error = %@", error);
//    }];

END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,966评论 25 709
  • 转自 iOS 面试常见问题最全梳理 序言 目前形势,参加到iOS队伍的人是越来越多,甚至已经到供过于求了。今年,找...
    ZMJun阅读 811评论 0 11
  • *面试心声:其实这些题本人都没怎么背,但是在上海 两周半 面了大约10家 收到差不多3个offer,总结起来就是把...
    Dove_iOS阅读 27,227评论 30 472
  • “要用三年的时间换一辈子的幸福,绝不用一辈子的时间来忏悔这三年”嘹亮振奋的口号声萦绕耳畔,斑驳的记忆填满心...
    Army_f0ca阅读 297评论 0 1
  • 十六君/文 8月22日凌晨3点22分,演员宋丹丹在微博晒出一组与病床上的母亲双手紧握的照片,配文:“母亲生命垂危,...
    十六君阅读 474评论 0 3