OC 实现定位功能

遵守代理协议

<CLLocationManagerDelegate>

创建manager,用于申请定位权限,或开始定位

@property (strong, nonatomic) CLLocationManager *mgr;

懒加载创建mgr

- (CLLocationManager *)mgr {
if (!_mgr) {
    _mgr = [CLLocationManager new];
}
return _mgr;
}

设置代理

self.mgr.delegate = self;
系统版本为ios8+

向用户申请权限,前台和后台都有权限 将 NSLocationAlwaysUsageDescriptionKey加入info.plist文件里.value随便写

[self.mgr requestAlwaysAuthorization];

向用户申请权限,只有在用的时候才开始定位 将NSLocationWhenInUseUsageDescriptionKey加入info.plist文件里.value随便写

[self.mgr requestWhenInUseAuthorization];
系统版本为ios7以下
    [self.mgr startUpdatingLocation];

用户是否同意授权

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    if (status == kCLAuthorizationStatusAuthorizedAlways || status ==  kCLAuthorizationStatusAuthorizedWhenInUse) {
        NSLog(@"用户授权成功");
        [self.mgr startUpdatingLocation];
    } else if (status == kCLAuthorizationStatusDenied) {
        NSLog(@"用户授权拒绝");

    }
}

###定位成功后的代理方法

- (void) locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {

//    NSLog(@"%s";,__func__);
//    locations数组按照顺序存放,最新的定位位置放在数组的最后一个

CLLocation *location = [locations lastObject];

//    NSLog(@"%@",[locations lastObject]);

NSLog(@;定位后的位置:%f, %f, %f;,location.coordinate.latitude, location.coordinate.longitude, location.speed);

//停止定位
[self.mgr stopUpdatingLocation];
}

iOSObjective-C

436 字

2015-03-10 18:08 +0900

2015-03-10 18:08 +0900

comments powered by Disqus