iOS獲取當前城市

1.倒入頭文件

#import <CoreLocation/CoreLocation.h>post

2.實現定位協議CLLocationManagerDelegateatom

3.定義定位屬性

@property(nonatomic,retain)CLLocationManager *locationManager;spa

4.開始定位3d

- (void)locatecode

{ci

    // 推判定位操做是否被贊成it

    if([CLLocationManager locationServicesEnabled]) {io

        self.locationManager = [[CLLocationManager alloc] init] ;編譯

        

        self.locationManager.delegate = self;ast

    }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) {

        // 提示用戶出錯緣由。可按住Option鍵點擊 KCLErrorDenied的查看不少其它出錯信息,可打印error.code值查找緣由所在

    }

}

相關文章
相關標籤/搜索