如果在一個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