为了账号安全,请及时绑定邮箱和手机立即绑定

如何获取用户当前的城市名称?

如何获取用户当前的城市名称?

阿波罗的战车 2019-11-05 16:16:37
您如何检索用户的当前城市名称?
查看完整描述

3 回答

?
弑天下

TA贡献1818条经验 获得超8个赞

您需要做的是设置一个CLLocationManager可以找到您当前坐标的坐标。使用当前坐标,您需要使用它MKReverseGeoCoder来找到您的位置。


- (void)viewDidLoad 

{  

    // this creates the CCLocationManager that will find your current location

    CLLocationManager *locationManager = [[[CLLocationManager alloc] init] autorelease];

    locationManager.delegate = self;

    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters;

    [locationManager startUpdatingLocation];

}


// this delegate is called when the app successfully finds your current location

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

{

    // this creates a MKReverseGeocoder to find a placemark using the found coordinates

    MKReverseGeocoder *geoCoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate];

    geoCoder.delegate = self;

    [geoCoder start];

}


// this delegate method is called if an error occurs in locating your current location

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error 

{

 NSLog(@"locationManager:%@ didFailWithError:%@", manager, error);

}


// this delegate is called when the reverseGeocoder finds a placemark

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFindPlacemark:(MKPlacemark *)placemark

{

    MKPlacemark * myPlacemark = placemark;

    // with the placemark you can now retrieve the city name

    NSString *city = [myPlacemark.addressDictionary objectForKey:(NSString*) kABPersonAddressCityKey];

}


// this delegate is called when the reversegeocoder fails to find a placemark

- (void)reverseGeocoder:(MKReverseGeocoder *)geocoder didFailWithError:(NSError *)error

{

    NSLog(@"reverseGeocoder:%@ didFailWithError:%@", geocoder, error);

}


查看完整回答
反对 回复 2019-11-05
?
湖上湖

TA贡献2003条经验 获得超2个赞

从iOS 5开始MKReverseGeoCoder不推荐使用!


因此,您想使用CLGeocoderwith CLLocationManager,非常简单,并且可以使用block。


例:


- (void)locationManager:(CLLocationManager *)manager

    didUpdateToLocation:(CLLocation *)newLocation

           fromLocation:(CLLocation *)oldLocation

{

   [self.locationManager stopUpdatingLocation];


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

    [geoCoder reverseGeocodeLocation:newLocation

                   completionHandler:^(NSArray *placemarks, NSError *error) {

                       for (CLPlacemark *placemark in placemarks) {

                           .... = [placemark locality];

                       }

                   }];

}

编辑:除了for in循环,您还可以执行以下操作:


NSString *locString = placemarks.count ? [placemarks.firstObject locality] : @"Not Found";


查看完整回答
反对 回复 2019-11-05
  • 3 回答
  • 0 关注
  • 917 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信