如何检索用户的当前城市名称?

你如何检索用户的当前城市名称?

你需要做的是设置一个CLLocationManager ,它可以find你当前的坐标。 使用当前坐标,您需要使用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); } 

从iOS 5 MKReverseGeoCoder已弃用!

所以你想用CLLocationManager来使用CLGeocoder ,非常简单,并且可以和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"; 

这对我来说工作得很好:

 CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; [geocoder reverseGeocodeLocation:self.locationManager.location completionHandler:^(NSArray *placemarks, NSError *error) { NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!"); if (error){ NSLog(@"Geocode failed with error: %@", error); return; } CLPlacemark *placemark = [placemarks objectAtIndex:0]; NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode); NSLog(@"placemark.country %@",placemark.country); NSLog(@"placemark.postalCode %@",placemark.postalCode); NSLog(@"placemark.administrativeArea %@",placemark.administrativeArea); NSLog(@"placemark.locality %@",placemark.locality); NSLog(@"placemark.subLocality %@",placemark.subLocality); NSLog(@"placemark.subThoroughfare %@",placemark.subThoroughfare); }]; 

如果有人试图从MKReverseGeocoder转到CLGeocoder,那么我写了一篇博文可能是有帮助http://jonathanfield.me/jons-blog/clgeocoder-example.html

基本上一个例子是,在创buildlocationManager和CLGeocoder对象之后,只需将此代码添加到viewDidLoad()中,然后制作一些标签或文本区域来显示数据。

  [super viewDidLoad]; locationManager.delegate = self; [locationManager startUpdatingLocation]; locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation; [self.CLGeocoder reverseGeocodeLocation: locationManager.location completionHandler: ^(NSArray *placemarks, NSError *error) { CLPlacemark *placemark = [placemarks objectAtIndex:0]; isoCountryCode.text = placemark.ISOcountryCode; country.text = placemark.country; postalCode.text= placemark.postalCode; adminArea.text=placemark.administrativeArea; subAdminArea.text=placemark.subAdministrativeArea; locality.text=placemark.locality; subLocality.text=placemark.subLocality; thoroughfare.text=placemark.thoroughfare; subThoroughfare.text=placemark.subThoroughfare; //region.text=placemark.region; }]; 

如果有人在Swift 3中需要它,我就是这么做的:

 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let location = locations.first! let coordinateRegion = MKCoordinateRegionMakeWithDistance(location.coordinate, 500, 500) self.location = location self.locationManager?.stopUpdatingLocation() // Drop a pin at user's Current Location let myAnnotation: MKPointAnnotation = CustomPointAnnotation() myAnnotation.coordinate = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude) myAnnotation.title = "Localização" self.mapViewMK.addAnnotation(myAnnotation) self.mapViewMK.setRegion(coordinateRegion, animated: true) self.locationManager?.stopUpdatingLocation() self.locationManager = nil // Get user's current location name let geocoder = CLGeocoder() geocoder.reverseGeocodeLocation(self.location!) { (placemarksArray, error) in if (placemarksArray?.count)! > 0 { let placemark = placemarksArray?.first let number = placemark!.subThoroughfare let bairro = placemark!.subLocality let street = placemark!.thoroughfare self.addressLabel.text = "\(street!), \(number!) - \(bairro!)" } } } 

您必须获取用户的当前位置,然后使用MKReverseGeocoder来识别城市。

在iPhone应用程序编程指南第8章中有很好的例子。一旦你有位置初始化地理编码器,设置委托,并从地标读取国家。 阅读MKReverseGeocodeDelegate的文档并创build方法:

  • reverseGeocoder:didFindPlacemark:
  • reverseGeocoder:didFailWithError:

     MKReverseGeocoder *geocoder = [[MKReverseGeocoder alloc] initWithCoordinate:newLocation.coordinate]; geocoder.delegate = self; [geocoder start]; 

您可以使用此代码获取当前城市: –

extension YourController:CLLocationManagerDelegate {func locationManager(manager:CLLocationManager,didUpdateLocations locations:[CLLocation]){

  CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in if (error != nil) { manager.stopUpdatingLocation() return } else { if placemarks!.count > 0 { let placeMarksArrray: NSArray = placemarks! let pm = placeMarksArrray[0] as! CLPlacemark self.displayLocationInfo(pm) manager.stopUpdatingLocation() } else { print("Problem with the data received from geocoder") } } }) } func displayLocationInfo(placemark: CLPlacemark!) { if (placemark != nil) { //stop updating location to save battery life locationLocation.stopUpdatingLocation() var tempString : String = "" if(placemark.locality != nil){ tempString = tempString + placemark.locality! + " " print(placemark.locality) } if(placemark.postalCode != nil){ tempString = tempString + placemark.postalCode! + " " print(placemark.postalCode) } if(placemark.administrativeArea != nil){ tempString = tempString + placemark.administrativeArea! + " " print(placemark.administrativeArea) } if(placemark.country != nil){ tempString = tempString + placemark.country! + " " } let dictForaddress = placemark.addressDictionary as! NSDictionary if let city = dictForaddress["City"] { print(city) } strLocation = tempString } } 
 // place the function code below in desire location in program. // [self getCurrentLocation]; -(void)getCurrentLocation { CLGeocoder *geocoder = [[CLGeocoder alloc] init] ; [geocoder reverseGeocodeLocation:self->locationManager.location completionHandler:^(NSArray *placemarks, NSError *error) { NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!"); if (error){ NSLog(@"Geocode failed with error: %@", error); return; } CLPlacemark *placemark = [placemarks objectAtIndex:0]; NSLog(@"placemark.ISOcountryCode %@",placemark.ISOcountryCode); NSLog(@"placemark.country %@",placemark.country); NSLog(@"placemark.locality %@",placemark.locality ); NSLog(@"placemark.postalCode %@",placemark.postalCode); NSLog(@"placemark.administrativeArea %@",placemark.administrativeArea); NSLog(@"placemark.locality %@",placemark.locality); NSLog(@"placemark.subLocality %@",placemark.subLocality); NSLog(@"placemark.subThoroughfare %@",placemark.subThoroughfare); }]; } 

阅读MKReverseGeocoder的文档 – 文档,指南和示例应用程序是由Apple提供的原因。