Obtener el nombre de ubicación de Latitude & Longitude en iOS

Quiero encontrar el nombre de la ubicación actual de latitud y longitud,

Aquí está el fragmento de código que probé pero mi registro muestra valores nulos en todos los lugares, excepto en placemark de placemark , placemark.ISOcountryCode placemark , placemark.ISOcountryCode y placemark.country

Quiero el valor de placemark.locality y placemark.subLocality pero muestra valores nulos.

 - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; // this creates the CCLocationManager that will find your current location locationManager = [[CLLocationManager alloc] init]; 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 { CLGeocoder *geocoder = [[CLGeocoder alloc] init]; [geocoder reverseGeocodeLocation:locationManager.location completionHandler:^(NSArray *placemarks, NSError *error) { NSLog(@"reverseGeocodeLocation:completionHandler: Completion Handler called!"); if (error){ NSLog(@"Geocode failed with error: %@", error); return; } NSLog(@"placemarks=%@",[placemarks objectAtIndex:0]); 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); }]; } // 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); } 

Gracias por adelantado.

EDITAR:

 - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation { CLGeocoder *geocoder = [[CLGeocoder alloc] init]; CLLocation *currentLocation = newLocation; if (currentLocation != nil) NSLog(@"longitude = %.8f\nlatitude = %.8f", currentLocation.coordinate.longitude,currentLocation.coordinate.latitude); // stop updating location in order to save battery power [locationManager stopUpdatingLocation]; [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { NSLog(@"Found placemarks: %@, error: %@", placemarks, error); if (error == nil && [placemarks count] > 0) { CLPlacemark *placemark = [placemarks lastObject]; // strAdd -> take bydefault value nil NSString *strAdd = nil; if ([placemark.subThoroughfare length] != 0) strAdd = placemark.subThoroughfare; if ([placemark.thoroughfare length] != 0) { // strAdd -> store value of current location if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark thoroughfare]]; else { // strAdd -> store only this value,which is not null strAdd = placemark.thoroughfare; } } if ([placemark.postalCode length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark postalCode]]; else strAdd = placemark.postalCode; } if ([placemark.locality length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark locality]]; else strAdd = placemark.locality; } if ([placemark.administrativeArea length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark administrativeArea]]; else strAdd = placemark.administrativeArea; } if ([placemark.country length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark country]]; else strAdd = placemark.country; } } }]; } 

Te estoy dando un fragmento que estoy usando para resolver la dirección. Incluyo el comentario también en el lugar necesario para entender el código. Además de eso, no dude en hacer cualquier pregunta de un fragmento si no comprende algo.

Escribir fragmento siguiente en el método didUpdateToLocation

 NSLog(@"didUpdateToLocation: %@", newLocation); CLLocation *currentLocation = newLocation; if (currentLocation != nil) NSLog(@"longitude = %.8f\nlatitude = %.8f", currentLocation.coordinate.longitude,currentLocation.coordinate.latitude); // stop updating location in order to save battery power [locationManager stopUpdatingLocation]; // Reverse Geocoding NSLog(@"Resolving the Address"); // “reverseGeocodeLocation” method to translate the locate data into a human-readable address. // The reason for using "completionHandler" ---- // Instead of using delegate to provide feedback, the CLGeocoder uses “block” to deal with the response. By using block, you do not need to write a separate method. Just provide the code inline to execute after the geocoding call completes. [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { NSLog(@"Found placemarks: %@, error: %@", placemarks, error); if (error == nil && [placemarks count] > 0) { placemark = [placemarks lastObject]; // strAdd -> take bydefault value nil NSString *strAdd = nil; if ([placemark.subThoroughfare length] != 0) strAdd = placemark.subThoroughfare; if ([placemark.thoroughfare length] != 0) { // strAdd -> store value of current location if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark thoroughfare]]; else { // strAdd -> store only this value,which is not null strAdd = placemark.thoroughfare; } } if ([placemark.postalCode length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark postalCode]]; else strAdd = placemark.postalCode; } if ([placemark.locality length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark locality]]; else strAdd = placemark.locality; } if ([placemark.administrativeArea length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark administrativeArea]]; else strAdd = placemark.administrativeArea; } if ([placemark.country length] != 0) { if ([strAdd length] != 0) strAdd = [NSString stringWithFormat:@"%@, %@",strAdd,[placemark country]]; else strAdd = placemark.country; } 

Donde strAdd devolverá la dirección mediante geolocalización.

¡Disfruta la progtwigción!

Método con bloque de finalización:

 typedef void(^addressCompletion)(NSString *); -(void)getAddressFromLocation:(CLLocation *)location complationBlock:(addressCompletion)completionBlock { __block CLPlacemark* placemark; __block NSString *address = nil; CLGeocoder* geocoder = [CLGeocoder new]; [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) { if (error == nil && [placemarks count] > 0) { placemark = [placemarks lastObject]; address = [NSString stringWithFormat:@"%@, %@ %@", placemark.name, placemark.postalCode, placemark.locality]; completionBlock(address); } }]; } 

Esta es la forma de usarlo:

 CLLocation* eventLocation = [[CLLocation alloc] initWithLatitude:_latitude longitude:_longitude]; [self getAddressFromLocation:eventLocation complationBlock:^(NSString * address) { if(address) { _address = address; } }]; 

Implementé la solución de Niru en Swift 3 , publicando aquí si alguien lo necesita:

 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!)" } } 

Si la ubicación que está tratando de obtener aparece en esta lista, entonces hay algo mal en su código.

http://developer.apple.com/library/ios/#technotes/tn2289/_index.html#//apple_ref/doc/uid/DTS40011305

de lo contrario, CLGeoCoder no tiene direcciones en otros países.

Enfrenté el mismo problema, así que usé esto para obtener la dirección. Da una dirección realmente precisa.

http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true_or_false

En primer lugar, filtre las ubicaciones en didUpdateToLocation para evitar el uso de ubicaciones en caché o incorrectas para la geoencoding

 NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow]; if (abs(locationAge) > 5.0) return; if (newLocation.horizontalAccuracy < 0) return; 

Además, intente alejar el método reverseGeoCoding de didUpdateToLocation

Una vez que tenga la latitude , los valores de longitude de una ubicación, puede usar CLGeocoder aquí, es un tutorial que podría ayudarlo.

use esta API para obtener los datos y pasar valores lat y long.

API para ubicación geográfica

En Swift 4.1 y Xcode 9.4.1, esta es una de mi solución. Aquí estoy usando la API de geoencoding para obtener la dirección completa. Con esta API puedo obtener los nombres de la aldea también.

Estoy usando reverseGeocodeLocation pero no está obteniendo los detalles de la dirección del pueblo ni los nombres de las aldeas, solo se está acercando por nombres de ciudades. Es una de las mejores soluciones …

 func getAddressForLatLng(latitude: String, longitude: String) { // Call this function let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?latlng=\(latitude),\(longitude)")//Here pass your latitude, longitude print(url!) let data = NSData(contentsOf: url! as URL) if data != nil { let json = try! JSONSerialization.jsonObject(with: data! as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary print(json) let status = json["status"] as! String if status == "OK" { if let result = json["results"] as? NSArray { if result.count > 0 { if let addresss:NSDictionary = result[0] as? NSDictionary { if let address = addresss["address_components"] as? NSArray { var newaddress = "" var number = "" var street = "" var city = "" var state = "" var zip = "" var country = "" if(address.count > 1) { number = (address.object(at: 0) as! NSDictionary)["short_name"] as! String } if(address.count > 2) { street = (address.object(at: 1) as! NSDictionary)["short_name"] as! String } if(address.count > 3) { city = (address.object(at: 2) as! NSDictionary)["short_name"] as! String } if(address.count > 4) { state = (address.object(at: 4) as! NSDictionary)["short_name"] as! String } if(address.count > 6) { zip = (address.object(at: 6) as! NSDictionary)["short_name"] as! String } newaddress = "\(number) \(street), \(city), \(state) \(zip)" print(newaddress) // OR //This is second type to fetch pincode, country, state like this type of data for i in 0.. 

Llame a esta función como esta

 self.getAddressForLatLng(latitude: "\(self.lat!)", longitude: "\(self.lng!)") 

Prueba esto

 [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) { //..NSLog(@"Found placemarks: %@, error: %@", placemarks, error); if (error == nil && [placemarks count] > 0) { placemark = [placemarks lastObject]; lblgetaddrees.text = [NSString stringWithFormat:@"%@,%@,%@,%@,%@,%@", placemark.subThoroughfare, placemark.thoroughfare, placemark.postalCode, placemark.locality, placemark.administrativeArea, placemark.country]; } else { //..NSLog(@"%@", error.debugDescription); } } ];