IOS-定位(顯示城市)

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);

}

}];

8.Git地址

github.com/baipeng1990/BPMapLocationDemo.git

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容