定位和反查位置信息要加載兩個動態(tài)庫 CoreLocation.framework 和 MapKit.framework 一個獲取坐標一個提供反查,可以通過配置NSLocationAlwaysUsageDescription或者 NSLocationWhenInUseUsageDescription來告訴用戶使用定位服務的目的,并且注意這個配置是必須的
import "ViewController.h"
import <UIKit/UIKit.h>
import <CoreLocation/CoreLocation.h>
import <MapKit/MapKit.h>
@interface ViewController ()<CLLocationManagerDelegate>
@property (nonatomic, strong) CLLocationManager *locationManager;
@property (nonatomic, strong) UIButton *button;
@end
@implementation ViewController
-
(void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.self.button = [UIButton buttonWithType:UIButtonTypeSystem];
_button.frame = CGRectMake(0, 100, 100, 30);
[_button setTitle:@"定位" forState:0];
[_button addTarget:self action:@selector(_startLocation) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button];
} -
(void)_startLocation {
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
self.locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;
self.locationManager.distanceFilter = 10.0f;
[self.locationManager startUpdatingLocation];
[self.locationManager requestWhenInUseAuthorization];
}
實現(xiàn)locationManager的代理方法
-
(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *newLocation = locations[0];
CLLocationCoordinate2D oCoordinate = newLocation.coordinate;
NSLog(@"經(jīng)度:%f焚志, 緯度: %f",oCoordinate.longitude,oCoordinate.latitude);
[self.locationManager stopUpdatingLocation];CLGeocoder *geoCoder = [[CLGeocoder alloc] init];
[geoCoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {for (CLPlacemark *place in placemarks) { NSDictionary *location = [place addressDictionary]; NSLog(@"國家:%@",[location objectForKey:@"Country"]); NSLog(@"城市:%@",[location objectForKey:@"State"]); NSLog(@"區(qū):%@",[location objectForKey:@"SubLocality"]); NSLog(@"位置:%@",place.name); NSLog(@"國家:%@",place.country); NSLog(@"城市:%@",place.locality); NSLog(@"區(qū):%@",place.subLocality); NSLog(@"街道:%@",place.thoroughfare); NSLog(@"子街道:%@",place.subThoroughfare); }
}];
}