如果在一個(gè)App的某個(gè)部分需要用到定位功能,比如查看附近的某些信息,那么需要用到CLLocationManager這個(gè)類(lèi)
導(dǎo)入#import <CoreLocation/CoreLocation.h>
首先創(chuàng)建locationManager對(duì)象
@property (nonatomic, strong) CLLocationManager *locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
[self requestLocation];
}
// 重寫(xiě)Getter方法
-(CLLocationManager *)locationManager{
if (!_locationManager) {
_locationManager = [[CLLocationManager alloc] init];
// 設(shè)置精度
_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// 100米內(nèi)不需要重新定位
_locationManager.distanceFilter = 100;
// 綁定委托
_locationManager.delegate = self;
}
return _locationManager;
}
// 請(qǐng)求定位
- (void) requestLocation{
// 請(qǐng)求用戶權(quán)限 開(kāi)啟定位
// 判斷當(dāng)前App是否開(kāi)啟定位服務(wù)
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
// 判斷是否已授權(quán)
if (status == kCLAuthorizationStatusNotDetermined) {
// 請(qǐng)求授權(quán)
[self.locationManager requestWhenInUseAuthorization];
}
// 如果關(guān)閉定位服務(wù) 彈框提示
else if (status == kCLAuthorizationStatusDenied){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"定位服務(wù)已關(guān)閉,請(qǐng)?jiān)谠O(shè)置中找到該應(yīng)用,然后開(kāi)啟定位服務(wù)" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];
[alertView show];
}
else{
[self.locationManager startUpdatingLocation];
}
}
#pragma mark - CLLocationDelegate
// 授權(quán)狀態(tài)改變時(shí)回調(diào)
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
if (status == kCLAuthorizationStatusDenied) {
NSLog(@"不允許");
}
else{
// 啟動(dòng)定位服務(wù)
[manager startUpdatingLocation];
}
}
- (void)locationManager:(CLLocationManager *)manager
didUpdateLocations:(NSArray *)locations {
// 先判斷有沒(méi)有位置信息
if (locations.count > 0) {
// 停止定位
[manager stopUpdatingLocation];
// 從數(shù)組中取出任意一個(gè)位置信息
CLLocation *location = [locations firstObject];
// 傳入位置信息 調(diào)用數(shù)據(jù)請(qǐng)求方法
[self requestNearApp:location.coordinate];
}
}