iOS 系统定位 强制定位

2020-01-16  本文已影响0人  奔跑吧小蚂蚁

官方说明

typedef NS_ENUM(NSInteger, CLError) {
    // 目前位置是未知的,但CL将继续努力
    kCLErrorLocationUnknown  = 0,         // location is currently unknown, but CL will keep trying
    // 获取用户位置或范围被拒绝
    kCLErrorDenied,                       // Access to location or ranging has been denied by the user
    // 一般情况下,网络相关的错误
    kCLErrorNetwork,                      // general, network-related error
    // 标题不能确定
    kCLErrorHeadingFailure,               // heading could not be determined
    // 位置区域监测被用户拒绝
    kCLErrorRegionMonitoringDenied,       // Location region monitoring has been denied by the user
    // 注册区域不能监控
    kCLErrorRegionMonitoringFailure,      // A registered region cannot be monitored
    // CL不能立即初始化区域监控
    kCLErrorRegionMonitoringSetupDelayed, // CL could not immediately initialize region monitoring
    // 如果这个防护事件被提交,提交将不会出现
    kCLErrorRegionMonitoringResponseDelayed, // While events for this fence will be delivered, delivery will not occur immediately
    // 地理编码没有结果
    kCLErrorGeocodeFoundNoResult,         // A geocode request yielded no result
    // 地理编码产生一部分结果
    kCLErrorGeocodeFoundPartialResult,    // A geocode request yielded a partial result
    // 地理编码被取消
    kCLErrorGeocodeCanceled,              // A geocode request was cancelled
    // 延迟模式失败
    kCLErrorDeferredFailed,               // Deferred mode failed
    // 延迟模式失败了,因为位置更新禁用或暂停
    kCLErrorDeferredNotUpdatingLocation,  // Deferred mode failed because location updates disabled or paused
    // 延迟模式不支持当前精准度
    kCLErrorDeferredAccuracyTooLow,       // Deferred mode not supported for the requested accuracy
    // 延迟模式不支持距离过滤器
    kCLErrorDeferredDistanceFiltered,     // Deferred mode does not support distance filters
    // 延迟模式请求取消前一个请求
    kCLErrorDeferredCanceled,             // Deferred mode request canceled a previous request
    // 测距杆不能执行
    kCLErrorRangingUnavailable,           // Ranging cannot be performed
    // 测距失败
    kCLErrorRangingFailure,               // General ranging failure
};

CLPlacemark 地区标签标识别

https://www.cnblogs.com/guitarandcode/p/5783805.html

//省
administrativeArea;
//市
locality;
//区
subLocality;
//街道
thoroughfare;
//子街道 门牌号等
subThoroughfare;
//具体位置
name;
//地址字典
addressDictionary

定位具体代码

- (void)startLocation {
    
    if ([CLLocationManager locationServicesEnabled] &&
        ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedWhenInUse || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusAuthorizedAlways)) {
        //定位功能可用
        _locationManager = [[CLLocationManager alloc]init];
        _locationManager.delegate = self;
        [_locationManager requestWhenInUseAuthorization];
        _locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters;
        _locationManager.distanceFilter = 10;
        [_locationManager startUpdatingLocation];
        
    } else {
        //[CLLocationManager authorizationStatus] ==kCLAuthorizationStatusDenied 拒绝获取定位
        //定位不能用
        [self locationPermissionAlert];
    }
}

//去设置时添加监控 收到监控后 从新定位
- (void)didBecomeActive {
    NSLog(@"%@", NSStringFromSelector(_cmd));
    [self startLocation];
    
    NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
    [notificationCenter removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    if ([error code] == kCLErrorDenied) {
        NSLog(@"访问被拒绝");
        [self locationPermissionAlert];
    }
    if ([error code] == kCLErrorLocationUnknown) {
        NSLog(@"无法获取位置信息");
    }
}

//定位代理经纬度回调
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    /*旧值*/
    CLLocation * currentLocation = [locations lastObject];
    CLGeocoder * geoCoder = [[CLGeocoder alloc]init];
    /*打印当前经纬度*/
    NSLog(@"当前纬度:%f",currentLocation.coordinate.latitude);
    NSLog(@"当前经度:%f",currentLocation.coordinate.longitude);
    self.strlatitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.latitude];
    self.strlongitude = [NSString stringWithFormat:@"%f",currentLocation.coordinate.longitude];
    
    //根据经纬度反向地理编译出地址信息
    __weak typeof(self) weakself = self;
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
    {
        if (array.count > 0) {
            CLPlacemark *placemark = [array objectAtIndex:0];
            
            weakself.administrativeArea = placemark.administrativeArea;
            weakself.locality = placemark.locality;
            weakself.subLocality = placemark.subLocality;
            weakself.thoroughfare = placemark.thoroughfare;
            weakself.subThoroughfare = placemark.subThoroughfare;
            weakself.name = placemark.name;
            NSLog(@"addressDictionary:%@",placemark.addressDictionary);
           //将获得的所有信息显示到label上
            NSLog(@"\nadministrativeArea:%@ \n locality:%@\n subLocality:%@\nthoroughfare:%@\n subThoroughfare:%@",placemark.administrativeArea,placemark.locality,placemark.subLocality,placemark.thoroughfare,placemark.subThoroughfare);
            
            NSLog(@"当前的具体地址:%@",placemark.name);/*具体地址 ** 市 ** 区** 街道*/
            self.locationLabel.textColor = [UIColor blackColor];
            self.locationLabel.text = [NSString stringWithFormat:@"%@ %@ %@",placemark.locality,placemark.subLocality,placemark.thoroughfare];
        }
        else if (error == nil && [array count] == 0)
        {
            NSLog(@"No results were returned.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
        [self.locationManager stopUpdatingLocation];
        self.locationManager.delegate = nil;
    }];
}

/// 获取当前位置权限提示图
- (void)locationPermissionAlert {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"请打开该应用的位置访问权限" message:@"我们通过位置信息获取相关数据" preferredStyle:UIAlertControllerStyleAlert];
    
    // Create the actions.
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
        
    }];
    
    UIAlertAction *otherAction = [UIAlertAction actionWithTitle:@"去设置" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        //后台进前台通知 UIApplicationDidBecomeActiveNotification
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(didBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
        
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        if ([[UIApplication sharedApplication]canOpenURL:url]) {
            [[UIApplication sharedApplication]openURL:url];
        }
    }];
    
    // Add the actions.
    [alertController addAction:cancelAction];
    [alertController addAction:otherAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

打印数据

2020-01-16 12:08:26.350008+0800 来拜[3068:701111] addressDictionary:{
    City = "\U4e0a\U6d77\U5e02";
    Country = "\U4e2d\U56fd";
    CountryCode = CN;
    FormattedAddressLines =     (
        "\U4e2d\U56fd\U4e0a\U6d77\U5e02\U6d66\U4e1c\U65b0\U533a\U9e64\U7acb\U897f\U8def3\U53f7"
    );
    Name = "\U9e64\U7acb\U897f\U8def3\U53f7";
    Street = "\U9e64\U7acb\U897f\U8def3\U53f7";
    SubLocality = "\U6d66\U4e1c\U65b0\U533a";
    SubThoroughfare = "3\U53f7";
    Thoroughfare = "\U9e64\U7acb\U897f\U8def";
}
2020-01-16 12:08:26.350281+0800 来拜[3068:701111] 
administrativeArea:(null) 
 locality:上海市
 subLocality:浦东新区
thoroughfare:鹤立西路
 subThoroughfare:3号
2020-01-16 12:08:26.350418+0800 来拜[3068:701111] 当前的具体地址:鹤立西路3号
上一篇下一篇

猜你喜欢

热点阅读