美文网首页
ios ~ 定位,位置信息

ios ~ 定位,位置信息

作者: 阳光下的叶子呵 | 来源:发表于2021-09-05 00:27 被阅读0次
app 定位.png

1、首先在info.plist文件中设置有关位置有关的权限设置:

1.导入coreLocation库
2.在info.plist里设置权限
(以下二选一,两个都添加默认使用NSLocationWhenInUseUsageDescription):NSLocationWhenInUseUsageDescription:允许在前台使用时获取GPS的描述NSLocationAlwaysUsageDescription:允许永久使用GPS的描述

info.plist位置权限设置.png

直接上代码:

// 引入:
#import <CoreLocation/CoreLocation.h>

// 遵守代理:
@interface ViewController () <CLLocationManagerDelegate>

/** 定位 */
@property CLLocationManager *locationmanager;//定位服务

@property (strong, nonatomic) NSString *strlatitude;//经度
@property (strong, nonatomic) NSString *strlongitude;//纬度
@property (strong, nonatomic) NSString *country; // 当前国家
@property (strong, nonatomic) NSString *province;
@property (strong, nonatomic) NSString *city;    // 当前城市
@property (strong, nonatomic) NSString *district;
@property (strong, nonatomic) NSString *street;

@end

    self.strlatitude = @"";
    self.strlongitude = @"";
    self.country =@"";//当前国家
    self.city = @"";//当前的城市
    self.street = @"";

详细代码:
-(IBAction)BtnLocationPress:(id)sender
{
    [self getLocation];
}


-(void)getLocation
{

    //判断定位功能是否允许
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationmanager = [[CLLocationManager alloc]init];
        self.locationmanager.delegate = self;
        [self.locationmanager requestAlwaysAuthorization];
        [self.locationmanager requestWhenInUseAuthorization];

        //设置寻址精度
        self.locationmanager.desiredAccuracy = kCLLocationAccuracyKilometer; //kCLLocationAccuracyBest;
        self.locationmanager.distanceFilter = 500.0; // 设定distanceFilter可以在用户移动指定的距离后,触发更新事件(500米更新一次)
        [self.locationmanager startUpdatingLocation];
    } else {
  
        //如果没有授权定位,提示开启
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"允许定位" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *ensure = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            [[UIApplication sharedApplication] openURL:url];
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertVC addAction:ensure];
        [alertVC addAction:cancel];
        [self.navigationController presentViewController:alertVC animated:YES completion:nil];

    }
}

#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    //[self.locationmanager stopUpdatingHeading];
    //旧址
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //打印当前的经度与纬度
    YMLog(@"当前经度=%f 当前纬度=%f 当前高度=%f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude, currentLocation.altitude);

    //反地理编码
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            NSString *currentCity = placeMark.locality;
            if (!currentCity) {
                currentCity = @"无法定位当前城市";
            }

           
            // 经纬度:
            self.strlatitude = [NSString stringWithFormat:@"%lf",currentLocation.coordinate.latitude];
            self.strlongitude = [NSString stringWithFormat:@"%lf",currentLocation.coordinate.longitude];;
            /*看需求定义一个全局变量来接收赋值(可以全局使用)*/
            //NSString *country =placeMark.country;//当前国家
            self.city = currentCity;//当前的城市
            [self.btn_location self.city forState:UIControlStateNormal];
            //NSString *street = placeMark.thoroughfare;
            

        }

/**
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            YMLog(@"当前用户所在城市:%@",placeMark.locality);
            YMLog(@"%@",placeMark.country);//当前国家
            YMLog(@"%@",placeMark.locality);//当前城市
            YMLog(@"%@",placeMark.subLocality);//当前位置
            YMLog(@"%@",placeMark.thoroughfare)//当前街道
            YMLog(@"%@",placeMark.name);//具体地址  市  区  街道

            NSString *address = [NSString stringWithFormat:@"%@%@%@",placeMark.locality,placeMark.subLocality,placeMark.name];
            YMLog(@"%@",address);
            [AppSingleInstance sharedInstance].currentUserAddress = address;

        } else if (error == nil && placemarks.count == 0) {
            YMLog(@"没有地址返回");
        } else if (error) {
            YMLog(@"%@",error);
        }
*/

    }];

}

#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{

if (error.code == kCLErrorDenied) {
        //访问被拒绝
        YMLog(@"位置访问被拒绝");
    } else if (error.code == kCLErrorLocationUnknown) {
        YMLog(@"无法获取用户信息");
    }
/**
    //设置提示提醒用户打开定位服务
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"允许定位提示" message:@"将前往设置开启定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString] options:@{} completionHandler:nil];
    }];

    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:okAction];
    [alert addAction:cancelAction];

    [self presentViewController:alert animated:YES completion:nil];
*/
}

二、笔记📒代码:

xcode定位设置的副本.png
/// 6、获取定位:经、纬度,判断是否开启定位权限
- (void)gainCurrentLoaction_latitudeAndLongitude {
    
    self.locationmanager = [[CLLocationManager alloc]init];
    self.locationmanager.delegate = self;
    [self.locationmanager stopUpdatingLocation];
    
    if ([CLLocationManager locationServicesEnabled]) {
        
//        self.locationmanager = [[CLLocationManager alloc]init];
        [self.locationmanager requestAlwaysAuthorization];
        [self.locationmanager requestWhenInUseAuthorization];

        //设置寻址精度
        self.locationmanager.desiredAccuracy = kCLLocationAccuracyKilometer; //kCLLocationAccuracyBest;
        self.locationmanager.distanceFilter = 500.0; // 设定distanceFilter可以在用户移动指定的距离后,触发更新事件(500米更新一次)
        [self.locationmanager startUpdatingLocation];
        
        
    } else {
        
        if (self.location_Latitude_Longitude_Block) {
            self.location_Latitude_Longitude_Block(NO, 0, 0);
        }
        
    }
    
}

#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    // locations提供了一连串的用户定位,我们只需要获取最后一个就好了(当前定位)
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    //打印当前的经度与纬度
//    NSLog(@"当前经度=%f 当前纬度=%f 当前高度=%f", currentLocation.coordinate.latitude, currentLocation.coordinate.longitude, currentLocation.altitude);
    

    //反地理编码
    [geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            NSString *currentCity = placeMark.locality;
            if (!currentCity) {
                currentCity = @"无法定位当前城市";
            }

            // 经纬度:
            double latitude = [[NSString stringWithFormat:@"%lf",currentLocation.coordinate.latitude] doubleValue];
            double longitude = [[NSString stringWithFormat:@"%lf",currentLocation.coordinate.longitude] doubleValue];
            
//            NSLog(@"经度 = %f,\n 纬度 = %f", longitude, latitude);
            
            NSDictionary *locationCurrent_longitude_latitude = @{
                @"longitude":[NSString stringWithFormat:@"%f", longitude],
                @"latitude":[NSString stringWithFormat:@"%f", latitude]
            };
            
            // 将当前经纬度保存在本地
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:locationCurrent_longitude_latitude forKey:@"LocationCurrent_longitude_latitude"];
            [userDefaults synchronize];
            
            /*
            if (self.location_Latitude_Longitude_Block) {
                self.location_Latitude_Longitude_Block(YES, latitude, longitude);
            }
             */
 
            GWLocationModel * currLocationModel = [[GWLocationModel alloc]init];
            currLocationModel.currlat = latitude;
            currLocationModel.currlon = longitude;
            
            [GWLocationContext sharedLocationModelInfoContext].locationModel= currLocationModel;
            [GWLocationUtilities SetCurrLocationMethod:currLocationModel];
            
        }

    }];
    
    // 停止位置更新
    [manager stopUpdatingLocation];

}

#pragma mark CoreLocation delegate (定位失败)
//定位失败后调用此代理方法
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{

    if (error.code == kCLErrorDenied) {
        //访问被拒绝
        NSLog(@"位置访问被拒绝");
    } else if (error.code == kCLErrorLocationUnknown) {
        NSLog(@"无法获取用户信息");
    }
    
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    if(status == kCLAuthorizationStatusNotDetermined)
       {
           //未决定,继续请求授权
//           [self gainCurrentLoaction_latitudeAndLongitude];
           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"允许定位"
                                                               message:@"请在设置中打开定位"
                                                              delegate:self
                                                     cancelButtonTitle:@"取消"
                                                     otherButtonTitles:@"确定",nil];
           [alertView show];
       }
       else if(status == kCLAuthorizationStatusRestricted)
       {
           //受限制,尝试提示然后进入设置页面进行处理(根据API说明一般不会返回该值)
           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"允许定位"
                                                               message:@"请在设置中打开定位"
                                                              delegate:self
                                                     cancelButtonTitle:@"取消"
                                                     otherButtonTitles:@"确定",nil];
           [alertView show];
       }
       else if(status == kCLAuthorizationStatusDenied)
       {
           //拒绝使用,提示是否进入设置页面进行修改
           UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"允许定位"
                                                               message:@"请在设置中打开定位"
                                                              delegate:self
                                                     cancelButtonTitle:@"取消"
                                                     otherButtonTitles:@"确定",nil];
           [alertView show];
       }
       else if(status == kCLAuthorizationStatusAuthorizedWhenInUse)
       {
           //授权使用,不做处理
       }
       else if(status == kCLAuthorizationStatusAuthorizedAlways)
       {
          //始终使用,不做处理
       }

    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        NSLog(@"点击了取消按钮");    
        if (self.location_Latitude_Longitude_Block) {
            self.location_Latitude_Longitude_Block(NO, 0, 0);
        }
    }
    else {
        NSLog(@"点击了确定按钮");
        if (self.location_Latitude_Longitude_Block) {
            self.location_Latitude_Longitude_Block(NO, 0, 0);
        }
        
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }
}


/// 没开启 定位权限时,设置权限
- (void)goToSettingLocationWithView:(UIView *)currentView {
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"允许定位" message:@"请在设置中打开定位" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ensure = [UIAlertAction actionWithTitle:@"打开定位" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:ensure];
    [alertVC addAction:cancel];
    [[LCM_Tool returnParentViewControllerWithView:currentView].navigationController presentViewController:alertVC animated:YES completion:nil];
    
}

相关文章

网友评论

      本文标题:ios ~ 定位,位置信息

      本文链接:https://www.haomeiwen.com/subject/yankwltx.html