1.App->info中添加請求定位說明。
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description
2.導(dǎo)入定位功能庫
App->Build Phases->Link Binary with Libraries->添加CoreLocation.framework
3.viewcontroller中導(dǎo)入corelocation.h
import <Corelocation/CoreLocation.h>
4.添加CLLocationManagerDelegate協(xié)議
@interface ViewController : UIViewController <CLLocationMangerDelegate>
5.初始化LocationManager對象
CLLocationManger *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManger.desiredAccuracy = kCLLocationAccuracyBest;
6.請求定位權(quán)限
if([ locationManager responseToSelector:@selector(requestAlwaysAuthorization) ]){
[ locationManager requestAlwaysAuthorization];
}
7.開始定位
[locationManager startUpdateLocation];
8.定位結(jié)果返回的方法
失敗 :-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{}
成功:-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
}
CLLocation對象包含經(jīng)緯度信息
9.轉(zhuǎn)換經(jīng)緯度為文字地址
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];