1.App->info中添加請(qǐng)求定位說(shuō)明绢陌。
Privacy - Location Always Usage Description
Privacy - Location When In Use Usage Description
2.導(dǎo)入定位功能庫(kù)
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對(duì)象
CLLocationManger *locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self;
locationManger.desiredAccuracy = kCLLocationAccuracyBest;
6.請(qǐng)求定位權(quán)限
if([ locationManager responseToSelector:@selector(requestAlwaysAuthorization) ]){
[ locationManager requestAlwaysAuthorization];
}
7.開(kāi)始定位
[locationManager startUpdateLocation];
8.定位結(jié)果返回的方法
失敗 :-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{}
成功:-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
}
CLLocation對(duì)象包含經(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對(duì)象
if(placeMarks.count>0){
CLPlaceMarker *placeMarker = placeMarks[0];
placemark.subThoroughfare;
placemark.thoroughfare;
placemark.postalCode;placemark.locality;
placemark.administrativeArea;
placemark.country贾富;
}
10.停止獲取定位信息
[locationManager stopUpdatingLocation];