1.在target->Build Phases->link Binary With Libraries中加入
CoreLocation.framework
2.在info.plist中加入
Privacy - Location Always Usage Description //總是開(kāi)啟 Privacy - Location When In Use Usage Description //在使用期間開(kāi)啟
3.在需要定位的頁(yè)面加入頭文件
#import <CoreLocation/CoreLocation.h>
#import <CoreLocation/CLLocationManagerDelegate.h>
4.聲明一個(gè)定位管理服務(wù)對(duì)象
@property(nonatomic ,strong)CLLocationManager *locationManager;
5.遵守定位管理服務(wù)協(xié)議
CLLocationManagerDelegate
6.在viewDidLoad中初始化定位服務(wù)對(duì)象- (void)viewDidLoad { [super viewDidLoad]; //定位服務(wù)初始化對(duì)象 _locationManager = [[CLLocationManager alloc]init ]; _locationManager.delegate = self; _locationManager.desiredAccuracy = kCLLocationAccuracyBest; _locationManager.distanceFilter = 1000.0f; if (![CLLocationManager locationServicesEnabled]) { NSLog(@"定位服務(wù)當(dāng)前可能尚未打開(kāi),請(qǐng)?jiān)O(shè)置打開(kāi)!"); return; }
- 實(shí)現(xiàn)
CLLocationManagerDelegate協(xié)議方法:
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
CLLocation *currentLocation = [locations lastObject]; CLGeocoder *geocoder = [[CLGeocoder alloc]init]; //反地理編碼 [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
MMLog(@"--array--%d---error--%@",(int)placemarks.count,error);
if (placemarks.count > 0) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSString *city = placemark.administrativeArea;//獲取城市
NSString *country = placemark.country;// 獲取國(guó)家
NSLog(@"位于:%@",city);
MMLog(@"%@",placemark.addressDictionary[@"Name"]);
}
}];
}
`
這只是作為真機(jī)測(cè)試