ios原生實現獲取用戶位置,用CLLocationManager實現定位


需求:打開APP獲取用戶所在城市

通過用系統CLLocationManager來實現,步驟如下:

1.在項目的Info.plist中添加兩個字段,如下圖所示:

2.在AppDelegate中初始化CLLocationManager對象,代碼如下:

#import "AppDelegate.h"
#import <CoreLocation/CoreLocation.h>
#import "MainViewController.h"

@interface AppDelegate ()<CLLocationManagerDelegate>

@property(nonatomic,strong)CLLocationManager *locationManager;

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    //判斷是否有定位權限
    if ([CLLocationManager locationServicesEnabled]) {
        // 開啟定位
        [self.locationManager startUpdatingLocation];
    }else{
        NSLog(@"系統定位尚未打開,請到【設置-隱私-定位服務】中手動打開");
    }
    
    return YES;
    
}

#pragma mark -定位設置
-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        // 創建CoreLocation管理對象
        CLLocationManager *locationManager = [[CLLocationManager alloc]init];
        // 定位權限檢查
        [locationManager requestWhenInUseAuthorization];
        // 設定定位精准度
        [locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        // 設置代理
        locationManager.delegate = self;
        
        _locationManager = locationManager;
    }
    return _locationManager;
    
}

3.實現CLLocationManager相應的代理方法,代碼如下

#pragma mark -代理方法,定位權限檢查
-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:{
            NSLog(@"用戶還未決定授權");
            // 主動獲得授權
            [self.locationManager requestWhenInUseAuthorization];
            break;
        }
        case kCLAuthorizationStatusRestricted:
        {
            NSLog(@"訪問受限");
            // 主動獲得授權
            [self.locationManager requestWhenInUseAuthorization];
            break;
        }
        case kCLAuthorizationStatusDenied:{
            // 此時使用主動獲取方法也不能申請定位權限
            // 類方法,判斷是否開啟定位服務
            if ([CLLocationManager locationServicesEnabled]) {
                NSLog(@"定位服務開啟,被拒絕");
            } else {
                NSLog(@"定位服務關閉,不可用");
            }
            break;
        }
        case kCLAuthorizationStatusAuthorizedAlways:{
            NSLog(@"獲得前后台授權");
            break;
        }
        case kCLAuthorizationStatusAuthorizedWhenInUse:{
            NSLog(@"獲得前台授權");
            break;
        }
        default:
            break;
    }
}
#pragma mark -獲取位置
- (void)locationManager:(CLLocationManager *)manager
   didUpdateLocations:(NSArray *)locations{
    
    CLLocation * newLocation = [locations lastObject];
    // 判空處理
    if (newLocation.horizontalAccuracy < 0) {
        NSLog(@"定位失敗,請檢查手機網絡以及定位");
        return;
    }
    //停止定位
    [self.locationManager stopUpdatingLocation];
    // 獲取定位經緯度
//    CLLocationCoordinate2D coor2D = newLocation.coordinate;
//    NSLog(@"緯度為:%f, 經度為:%f", coor2D.latitude, coor2D.longitude);
    
    // 創建編碼對象,獲取所在城市
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    // 反地理編碼
    [geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error != nil || placemarks.count == 0) {
            return ;
        }
        // 獲取地標
        CLPlacemark *placeMark = [placemarks firstObject];
//        NSLog(@"獲取地標 = %@,",placeMark.locality);
    }];
   
}
#pragma mark -定位失敗
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
//     NSLog(@"定位失敗,請檢查手機網絡以及定位");
}

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM