定位

如果在一個App的某個部分需要用到定位功能,比如查看附近的某些信息,那么需要用到CLLocationManager這個類
導入#import <CoreLocation/CoreLocation.h>

首先創(chuàng)建locationManager對象

@property (nonatomic, strong) CLLocationManager *locationManager;
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self requestLocation];
}
// 重寫Getter方法
-(CLLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[CLLocationManager alloc] init];
        // 設(shè)置精度
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        // 100米內(nèi)不需要重新定位
        _locationManager.distanceFilter = 100;
        // 綁定委托
        _locationManager.delegate = self;
    }
    return _locationManager;
}
// 請求定位
- (void) requestLocation{
    // 請求用戶權(quán)限 開啟定位
    // 判斷當前App是否開啟定位服務
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    // 判斷是否已授權(quán)
    if (status == kCLAuthorizationStatusNotDetermined) {
        // 請求授權(quán)
        [self.locationManager requestWhenInUseAuthorization];
    }
    // 如果關(guān)閉定位服務 彈框提示
    else if (status == kCLAuthorizationStatusDenied){
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"定位服務已關(guān)閉,請在設(shè)置中找到該應用,然后開啟定位服務" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
        [alertView show];
    }
    else{
        [self.locationManager startUpdatingLocation];
    }
}
#pragma mark - CLLocationDelegate
// 授權(quán)狀態(tài)改變時回調(diào)
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    if (status == kCLAuthorizationStatusDenied) {
        NSLog(@"不允許");
    }
    else{
        // 啟動定位服務
        [manager startUpdatingLocation];
    }
}
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations {
    // 先判斷有沒有位置信息
    if (locations.count > 0) {
        // 停止定位
        [manager stopUpdatingLocation];
        // 從數(shù)組中取出任意一個位置信息
        CLLocation *location = [locations firstObject];
        // 傳入位置信息 調(diào)用數(shù)據(jù)請求方法
        [self requestNearApp:location.coordinate];
    }
}
nearApp.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容