1.導(dǎo)入框架
Xcode中添加 CoreLocation.framework
2.info.plist文件添加描述
3.導(dǎo)入頭文件
#import <CoreLocation/CoreLocation.h>
4.聲明管理者和城市
{ ? ?
NSString * currentCity; //當(dāng)前城市
}
@property (nonatomic, strong) CLLocationManager *locationManager;
5.初始化
self.locationManager= [[CLLocationManageralloc]init];
self.locationManager.delegate=self;
[_locationManagerrequestWhenInUseAuthorization];
currentCity= [[NSStringalloc]init];
6.開(kāi)始定位
判斷定位是否打開(kāi)
- (void)locate { ? ?
//判斷定位功能是否打開(kāi) ? ?
if ([CLLocationManager locationServicesEnabled]) { ? ? ? ? NSLog(@"開(kāi)始定位"); ? ? ? ?
[self.locationManager startUpdatingLocation]; ? ?
} ? ?
定位未開(kāi)啟,去打開(kāi)定位
UIAlertController* alertVC = [UIAlertControlleralertControllerWithTitle:@"允許\"定位\"提示"message:@"請(qǐng)?jiān)谠O(shè)置中打開(kāi)定位"preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertActionactionWithTitle:@"打開(kāi)定位"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction*_Nonnullaction) {
//打開(kāi)定位設(shè)置
NSURL*settingsURL = [NSURLURLWithString:UIApplicationOpenSettingsURLString];
[[UIApplicationsharedApplication]openURL:settingsURL];
}];
UIAlertAction* cancel = [UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:^(UIAlertAction*_Nonnullaction) {
}];
[alertVCaddAction:cancel];
[alertVCaddAction:ok];
[selfpresentViewController:alertVCanimated:YEScompletion:nil];
7.代理方法
? ??????-(void)locationManager:(CLLocationManager*)manager didUpdateLocations:(NSArray *)locations
????1.獲取經(jīng)緯度
CLLocation*currentLocation = [locationslastObject];
CLLocationCoordinate2Dcoordinate = currentLocation.coordinate;
NSLog(@"緯度%f 經(jīng)度%f",coordinate.latitude,coordinate.longitude);
????2.獲取城市
CLGeocoder* geoCoder = [[CLGeocoderalloc]init];
//反編碼
[geoCoderreverseGeocodeLocation:currentLocationcompletionHandler:^(NSArray *_Nullableplacemarks,NSError*_Nullableerror) {
if(placemarks.count>0) {
CLPlacemark*placeMark = placemarks[0];
currentCity= placeMark.locality;
if(!currentCity) {
currentCity=@"無(wú)法定位當(dāng)前城市";
}
//NSLog(@"%@",currentCity); //這就是當(dāng)前的城市
//NSLog(@"%@",placeMark.name);//具體地址:xx市xx區(qū)xx街道
_cityLabel.text=currentCity;
_placeLabel.text= placeMark.name;
}
elseif(error ==nil&& placemarks.count==0) {
NSLog(@"No location and error return");
}
elseif(error) {
NSLog(@"location error: %@ ",error);
}
}];