iOS8以后,利用CoreLocation 獲取當(dāng)前城市經(jīng)緯度和城市名稱

要利用CoreLocation,必須在frameworks里面加入“CoreLocation.framework”。

接著在info.plist文件中加入下面兩個(gè)key,type為string類型,

value值自己定義,也可以不寫,

NSLocationAlwaysUsageDescription

NSLocationWhenInUseUsageDescription

如圖:



1.? .h里導(dǎo)入<CoreLocation/CoreLocation.h>

實(shí)現(xiàn)CLLocationManagerDelegate

#import <CoreLocation/CoreLocation.h>

@interfaceHomeViewController :UIViewController<CLLocationManagerDelegate>

{

CLLocationManager*locationManager;

}

@property(strong,nonatomic)CLLocationManager*locationManager;

@end

2. ?.m里只需兩個(gè)方法

//TODO:定位代理經(jīng)緯度回調(diào)

- (void)locationManager:(CLLocationManager*)manager didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation {

[locationManager ? stopUpdatingLocation];

NSLog(@"定位成功...");

NSLog(@"%@",[NSString ? stringWithFormat:@"經(jīng)度:%3.5f\n緯度:%3.5f",newLocation.coordinate.latitude,newLocation.coordinate.longitude]);

CLGeocoder* geoCoder = [[CLGeocoder ?alloc]init];

//根據(jù)經(jīng)緯度反向地理編譯出地址信息

[geoCoderreverseGeocodeLocation:newLocationcompletionHandler:^(NSArray*array,NSError*error){

if(array.count>0){

CLPlacemark*placemark = [array objectAtIndex:0];

//將獲得的所有信息顯示到導(dǎo)航欄上

_titleLab.text= [NSString stringWithFormat:@"%@%@",placemark.locality,placemark.subLocality];

//獲取城市

NSString*city = placemark.locality;

if(!city) {

//四大直轄市的城市信息無法通過locality獲得,只能通過獲取省份的方法來獲得(如果city為空,則可知為直轄市)

city = placemark.administrativeArea;

}

NSLog(@"city = %@", city);

}

else if(error ==nil&& [array ?count] ==0)

{

NSLog(@"No results were returned.");

}

else if(error !=nil)

{

NSLog(@"An error occurred = %@", error);

}

}];

//系統(tǒng)會(huì)一直更新數(shù)據(jù),直到選擇停止更新,因?yàn)槲覀冎恍枰@得一次經(jīng)緯度即可,所以獲取之后就停止更新

[manager ?stopUpdatingLocation];

}

//TODO:初始化定位管理器

- (void)initializeLocationService {

//初始化定位管理器

_locationManager= [[CLLocationManager ? ?alloc]init];

//設(shè)置代理

_locationManager.delegate=self;

//設(shè)置定位精確度到米

_locationManager.desiredAccuracy=kCLLocationAccuracyBest;

//設(shè)置過濾器為無

_locationManager.distanceFilter=kCLDistanceFilterNone;

//開始定位

[_locationManager ?requestAlwaysAuthorization];//這句話ios8以上版本使用。

[_locationManager ?startUpdatingLocation];

}

最后不要忘了在viewDidLoad中初始化定位管理器

- (void)viewDidLoad {

[self ? initializeLocationService];

}

本人是用真機(jī)調(diào)試成功的.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容