如何使iOS获取的地理位置有效

关于CLLocationManager获取地理位置遇到的一些小事;

项目使arc  

第一步:获取是否允许定位

-(BOOL)IsLocationServicesEnabled
{
    /**
     * [CLLocationManager locationServicesEnabled] 系统设置允许定位服务是否开启
     * [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied  APP是否开启定位服务
     */
    return ([CLLocationManager locationServicesEnabled] && [CLLocationManager authorizationStatus] != kCLAuthorizationStatusDenied);
}

第二步:开始定位,创建全局变量 (个人理解:如果CLLocationManager的属性不是全局的在ARC项目中,出了函数体 局部变量就会被release)

@property (nonatomic, strong) CLLocationManager *userLocation;

  

-(void)getUserLocationInfomation
{
    if ([self IsLocationServicesEnabled])
    {
        
        if (!self.userLocation)
        {
            self.userLocation = [[CLLocationManager alloc]init];
        }
        
        self.userLocation.delegate = self;
        //选择定位的方式为最优的状态
        self.userLocation.desiredAccuracy = kCLLocationAccuracyBest;
        //发生事件的最小距离间隔
        self.userLocation.distanceFilter = kCLDistanceFilterNone;
        [self.userLocation startUpdatingLocation];
    }
}

第三部分:delegate回调

#pragma locationManager delegate

-(void)locationManager:(CLLocationManager *)manager
   didUpdateToLocation:(CLLocation *)newLocation
          fromLocation:(CLLocation *)oldLocation
{
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];
    if (locationAge > 180.0) return;
    // 测试该水平精度是否有效
    if (newLocation.horizontalAccuracy < 0) return;
    // 写你的代码 现在拿到的newLocation是有效的
[self.userLocation stopUpdatingLocation];
self.userLocation.delegate = nil;

}

-(void)locationManager:(CLLocationManager *)manager
      didFailWithError:(NSError *)error
{
    
}

  

转载于:https://www.cnblogs.com/swiftAngel/p/4039596.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值