iOS 獲取當前城市

2022-05-08 23:33:09 字數 1898 閱讀 1471

1.倒入標頭檔案 

#import

2.實現定位協議cllocationmanagerdelegate

3.定義定位屬性 

@property(nonatomic,retain)cllocationmanager *locationmanager;

4.開始定位

- (void)locate

// 判斷定位操作是否被允許

if([cllocationmanager locationservicesenabled]) else {

//提示使用者無法進行定位操作

uialertview *alertview = [[uialertview alloc]initwithtitle:

@"提示" message:@"定位不成功 ,請確認開啟定位" delegate:nil cancelbuttontitle:@"取消" otherbuttontitles:@"確定", nil];

[alertview show];

// 開始定位

[self.locationmanager startupdatinglocation];

5.實現定位協議**方法 

#pragma mark - corelocation delegate

-(void)locationmanager:(cllocationmanager *)manager didupdatelocations:(nsarray *)locations

//此處locations儲存了持續更新的位置座標值,取最後乙個值為最新位置,如果不想讓其持續更新位置,則在此方法中獲取到乙個值之後讓locationmanager stopupdatinglocation

cllocation *currentlocation = [locations lastobject];

// 獲取當前所在的城市名

clgeocoder *geocoder = [[clgeocoder alloc] init];

//根據經緯度反向地理編譯出位址資訊

[geocoder reversegeocodelocation:currentlocation completionhandler:^(nsarray *array, nserror *error)

if (array.count > 0)

clplacemark *placemark = [array objectatindex:0];

//將獲得的所有資訊顯示到label上

nslog(@"%@",placemark.name);

//獲取城市

nsstring *city = placemark.locality;

if (!city) {

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

city = placemark.administrativearea;

self.cityname = city;

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

nslog(@"no results were returned.");

else if (error != nil)

nslog(@"an error occurred = %@", error);

//系統會一直更新資料,直到選擇停止更新,因為我們只需要獲得一次經緯度即可,所以獲取之後就停止更新

[manager stopupdatinglocation];

- (void)locationmanager:(cllocationmanager *)manager

didfailwitherror:(nserror *)error {

if (error.code == kclerrordenied) {

IOS 根據ip獲取當前城市的編號

ios 通過ip位址獲取當前城市的編號 解析 通過ip 獲取城市天氣 nsurl url nsurl urlwithstring 定義乙個nserror物件,用於捕獲錯誤資訊 nserror error nsstring jsonstring nsstring stringwithcontentso...

IOS獲取當前位置

ios支援三種檢測當前位置的方式 手機基站 wi fi 和gps,其中gps是經度最高的,同時也是最耗費手機電量的。一般情況下在室內是無法通過gps獲取位置資訊的,通過wi fi獲取位置的原理是通過網路提供商的ip位址資訊來獲取位置,經度不是很高,最後是通過手機基站獲取位置,手機開機後會連線附近的基...

iOS獲取當前的位置

在ios中獲取當前的位置資訊,包括 維度 經度 城市 街道 路口等資訊 使用步驟 1 2 3 manager cllocationmanager alloc init manager.delegate self manager startupdatinglocation 由於在ios8中,需要開發者...