1.App->info中添加请求定位说明。
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description
2.导入定位功能库
App->Build Phases->Link Binary with Libraries->添加CoreLocation.framework
3.viewcontroller中导入corelocation.h
import <Corelocation/CoreLocation.h>
4.添加CLLocationManagerDelegate协议
@interface ViewController : UIViewController <CLLocationMangerDelegate>
5.初始化LocationManager对象
CLLocationManger *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManger.desiredAccuracy = kCLLocationAccuracyBest;
6.请求定位权限
if([ locationManager responseToSelector:@selector(requestAlwaysAuthorization) ]){
[ locationManager requestAlwaysAuthorization];
}
7.开始定位
[locationManager startUpdateLocation];
8.定位结果返回的方法
失败 :-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{}
成功:-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
}
CLLocation对象包含经纬度信息
9.转换经纬度为文字地址
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location preferredLocation:[NSLocale systemLocale] completionHandler:^(NSArray *placeMarks,NSError *error){
}
placeMarks包含CLPlaceMarker对象
if(placeMarks.count>0){
CLPlaceMarker *placeMarker = placeMarks[0];
placemark.subThoroughfare;
placemark.thoroughfare;
placemark.postalCode;placemark.locality;
placemark.administrativeArea;
placemark.country;
}
10.停止获取定位信息
[locationManager stopUpdatingLocation];