1、首先得引入CoreLocation系統(tǒng)框架
2赴肚、導(dǎo)入頭文件 遵循代理
import <CoreLocation/CoreLocation.h>
<CLLocationManagerDelegate>
3届谈、在info.plist中打開定位權(quán)限
3垄提、代碼實現(xiàn)
@property (nonatomic, strong) CLLocationManager* locationManager;
- (void)viewDidLoad {
[super viewDidLoad];
//檢測定位功能是否開啟
if([CLLocationManager locationServicesEnabled]){
if(!_locationManager){
self.locationManager = [[CLLocationManager alloc] init];
if([self.locationManager respondsToSelector:@selector(requestWhenInUseAuthorization)]){
[self.locationManager requestWhenInUseAuthorization];
[self.locationManager requestAlwaysAuthorization];
}
//設(shè)置代理
[self.locationManager setDelegate:self];
//設(shè)置定位精度
[self.locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
//設(shè)置距離篩選
[self.locationManager setDistanceFilter:100];
//開始定位
[self.locationManager startUpdatingLocation];
//設(shè)置開始識別方向
[self.locationManager startUpdatingHeading];
}
}else{
UIAlertController *alertView = [UIAlertController alertControllerWithTitle:@"您沒有開啟定位功能" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
[alertView addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alertView animated:YES completion:nil];
}
}
這里返回一個[placemark addressDictionary]的字典 打印一下可以看到字典里面的各種key领炫,想用哪個key直接替換掉即可
//反地理編碼
- (void)reverseGeocoder:(CLLocation *)currentLocation {
CLGeocoder* geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"array == %@",placemarks);
if(error || placemarks.count == 0){
NSLog(@"error = %@",error);
}else{
CLPlacemark* placemark = placemarks.firstObject;
NSLog(@"dic == %@",[placemark addressDictionary]);
NSLog(@"placemark:%@",[[placemark addressDictionary] objectForKey:@"Street"]);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"您的位置" message:[[placemark addressDictionary] objectForKey:@"Street"] preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:nil]];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
//定位成功以后調(diào)用
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations {
[self.locationManager stopUpdatingLocation];
CLLocation* location = locations.lastObject;
[self reverseGeocoder:location];
}