How get zipCode from CLPlacemark , I get it always is null? - cllocationmanager

Here's a piece of sample code:
[_geoCoder reverseGeocodeLocation:self.locationManager.location // You can pass aLocation here instead
completionHandler:^(NSArray *placemarks, NSError *error) {
dispatch_async(dispatch_get_main_queue(),^ {
// do stuff with placemarks on the main thread
if (placemarks.count == 1) {
CLPlacemark *place = [placemarks objectAtIndex:0];
// NSLog([place postalCode]);
NSString* addressString1 = [place thoroughfare];
addressString1 = [addressString1 stringByAppendingString:[NSString stringWithFormat:#"%#",[place.addressDictionary objectForKey:(NSString*)kABPersonAddressZIPKey]]];//
NSLog(#"%#",addressString1);// is null ??
NSlog(#"%#",place.postalCode);//is null ??
//[self performSelectorInBackground:#selector(log) withObject:nil];
}
});
}];

I guess you probably only had a 'bad' coordinate, where no zip code exists. Try the following snippet. It should display various information and the zip code '80802' at the end:
CLLocationCoordinate2D myCoordinates = { 48.167222, 11.586111 };
CLLocation *location = [[CLLocation alloc]initWithLatitude:myCoordinates.latitude longitude:myCoordinates.longitude];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"%d Placemarks %#", placemarks.count, placemarks);
CLPlacemark *place = [placemarks objectAtIndex:0];
NSLog(#"Placemark %#", place);
NSLog(#"Address Dictionary: %#", place.addressDictionary);
NSLog(#"Zip key %#", [place.addressDictionary objectForKey:(NSString *)kABPersonAddressZIPKey]);
}];
Insert different coordinates in the first line and experiment yourself.

Related

[__NSCFNumber rangeOfCharacterFromSet:]: unrecognized selector sent to instance 0xb000000000005f53

I'm trying to convert my lat long into address using method:
#pragma mark:convert latLong to address
-(void)getMerchantAddress:(NSDictionary *)dict
{
double lata = [[dict valueForKey:#"user_lat"] doubleValue];
double longa = [[dict valueForKey:#"user_long"] doubleValue];
NSLog(#"%f",lata);
NSLog(#"%f",longa);
CLLocation *LocationAtual = [[CLLocation alloc]initWithLatitude:lata longitude:longa];
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder reverseGeocodeLocation:LocationAtual completionHandler:^(NSArray *placemarks, NSError *error)
{
if(placemarks && placemarks.count > 0)
{
CLPlacemark *placemark= [placemarks objectAtIndex:0];
NSArray *lines = placemark.addressDictionary[ #"FormattedAddressLines"];
NSString *addressString = [lines componentsJoinedByString:#","];
_usrtAddressLbl.text = addressString;
_userAddressLbl.text = addressString;
}
}];
}
my app crash # point
[geocoder reverseGeocodeLocation:LocationAtual completionHandler:^(NSArray *placemarks, NSError *error)
Error showing:
[__NSCFNumber rangeOfCharacterFromSet:]: unrecognized selector sent to instance 0xb000000000005f53
How can I resolve it. Thanks in advance.
Try this its working for me
-(void)getMerchantAddress:(NSDictionary *)dict
{
float lata = [[dict objectForKey:#"user_lat"] floatValue];
float longa = [[dict objectForKey:#"user_long"] floatValue];
CLGeocoder *ceo = [[CLGeocoder alloc]init];
CLLocation *loc = [[CLLocation alloc]initWithLatitude:lata longitude:longa]; //insert your coordinates
[ceo reverseGeocodeLocation:loc
completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
if (placemark) {
NSLog(#"placemark %#",placemark);
//String to hold address
strAddress = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
NSLog(#"addressDictionary %#", placemark.addressDictionary);
}else {
}
}
];
}

How To return a value From block in iOS

Im using google geocode Svc to get Lat and Lng from the Address,Some times Google geocode Svc is getting failed(Because of toomany counts per second or perday ), So i want to use Default Geocoder Svc provided by Apple.
See here My code
-(void)getLatandlongfromAddress
{
CLLocationCoordinate2D Coordinate=[self geoCodeUsingAddress:#"orlando"];
}
- (CLLocationCoordinate2D)geoCodeUsingAddress:(NSString *)address
{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]];
NSError *err = nil;
NSMutableDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err];
if (!err)
{
NSLog(#"status = %#",[jsonDict objectForKey:#"status"]);
if ([[jsonDict objectForKey:#"status"] isEqualToString:#"OK"])
{
//If status is cmng Im returned lat and long
}
else
{
// I want to use geocode Svc
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:#"Orlando 32835" completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(#"%#", error);
} else {
NSLog(#"%#",placemarks);
CLPlacemark *placemark = [placemarks lastObject];
}
}];
}
}
}
Guide me with any idea, Thanks..
There are several errors in your code:
If you call [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&err]; and pass kNilOptions as the options parameter you don't get back a mutable dictionary but an immutable one.
You should not check if there is no error but instead if your data is not nil.
Here is your corrected code (including the completion handler):
- (CLLocationCoordinate2D)geoCodeUsingAddress:(NSString *)address completionHandler:(void (^)(CLLocation *location, NSError *error))completionHandler {
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:req]]; // Whatever `req` is...
NSError *jsonError = nil;
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&jsonError];
if (jsonDict) {
NSLog(#"status = %#", [jsonDict objectForKey:#"status"]);
if ([[jsonDict objectForKey:#"status"] isEqualToString:#"OK"]) {
// If status is cmng Im returned lat and long
// Get them from you local file
CLLocationDegrees latitude = 30.0;
CLLocationDegrees longitude = 50.0;
CLLocation *location = [[CLLocation alloc] initWithLatitude:latitude longitude:longitude];
completionHandler(location, nil);
} else {
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:#"Orlando 32835" completionHandler:^(NSArray *placemarks, NSError *error) {
if (placemarks.count) {
NSLog(#"%#",placemarks);
CLPlacemark *placemark = [placemarks lastObject];
completionHandler(placemark.location, nil);
} else {
NSLog(#"%#", error);
completionHandler(nil, error);
}
}];
}
} else {
// Populate the error
completionHandler(nil, [NSError errorWithDomain:#"YOUR_DOMAIN" code:1000 userInfo:nil]);
}
}
You call it like any other method with a completion handler:
[self geoCodeUsingAddress:#"Orlando 32835" completionHandler:^(CLLocation *location, NSError *error) {
if (location) {
// Use location
} else {
NSLog(#"Error: %#", error.userInfo);
}
}];

Getting Postal Code using CLGeocoder

I'm trying to get the postal code when my map region has changed by using CLGeocoder:
CLLocation *location = [[CLLocation alloc] initWithLatitude:13.184098 longitude:77.725978];
- (void)mapView:(MKMapView *)mapView regionDidChangeAnimated:(BOOL)animated
{
CLLocation *location=[[CLLocation alloc] initWithLatitude:13.184098 longitude:77.725978];
[self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
{
if (!(error))
{
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(#"placemark %#",placemark);
NSString *Zipcode = [[NSString alloc]initWithString:placemark.postalCode];
NSLog(#"%#",Zipcode);
}
else
{
NSLog(#"Geocode failed with error %#", error); // Error handling must required
}
}];
}
i am getting response like this
{ Country = India; CountryCode = IN; FormattedAddressLines = ( Amarwara, "Madhya Pradesh", India ); Name = Amarwara; State = "Madhya Pradesh"; SubAdministrativeArea = Chhindwara; SubLocality = Amarwara; }
I'm able to get the postal code for the first time. When the region changes, I try to reverse geocode the postal code. I even tried setting the location explicitly (line 1) and it's still returning null postal code. Can any one help this strange bug?
Try this
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocation *newLocation = [[CLLocation alloc]initWithLatitude:21.1700
longitude:72.8300];
[geocoder reverseGeocodeLocation:newLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(#"Geocode failed with error: %#", error);
return;
}
if (placemarks && placemarks.count > 0)
{
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary =
placemark.addressDictionary;
NSLog(#"%# ", addressDictionary);
NSString *address = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [addressDictionary
objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *state = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStateKey];
NSString *zip = [addressDictionary
objectForKey:(NSString *)kABPersonAddressZIPKey];
NSLog(#"%# %# %# %#", address,city, state, zip);
}
}];

Initialize an property with data from a block

I want to initialize a CLLocationCoordinate2D property with a variable in a block.
in my company.h file:
#property CLLocationCoordinate2D cllocation;
in my company.m file
NSString *addressComplete = [NSString stringWithFormat:#"%# %d %#", address,(int) plz, place];
[self convertAddress:addressComplete];
-(void)convertAddress:(NSString*) address
{
NSString *location = address;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
_cllocation.longitude = placemark.location.coordinate.longitude;
_cllocation.latitude = placemark.location.coordinate.latitude;
}
}
];
NSLog(#"longitude: %f", _cllocation.longitude);
}
NSLog shows _cllocation as 0.0000.
How can i get this to work?
This is because statements in block are executed after NSLog statement. You are printing result before assigning. Move NSLog inside the block.
-(void)convertAddress:(NSString*) address
{
NSString *location = address;
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
[geocoder geocodeAddressString:location
completionHandler:^(NSArray* placemarks, NSError* error){
if (placemarks && placemarks.count > 0) {
CLPlacemark *topResult = [placemarks objectAtIndex:0];
MKPlacemark *placemark = [[MKPlacemark alloc] initWithPlacemark:topResult];
_cllocation.longitude = placemark.location.coordinate.longitude;
_cllocation.latitude = placemark.location.coordinate.latitude;
NSLog(#"longitude: %f", _cllocation.longitude);
}
}
];
}

Easiest way of getting reverse geocoded current location from iOS

I saw from another question here : Determine iPhone user's country that it is possible to get the current country the user of the iPhone is in.
And that is quite convenient for many uses. However, would it be possible to go even deeper and infer from iOS (if it has the information) which state or city the user is in as well?
I suppose reverse geocoding services would be the next step if things weren't possible.. Are there even such things as a reverse geocoding service you can hire for your app though?
MKReverseGeocoder is deprecated in iOS 5, now it's CLGeocoder
- (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];
}
}];
}
CLGeocoder *geocoder = [[CLGeocoder alloc] init];
CLLocation *newLocation = [[CLLocation alloc]initWithLatitude:21.1700
longitude:72.8300];
[geocoder reverseGeocodeLocation:newLocation
completionHandler:^(NSArray *placemarks, NSError *error) {
if (error) {
NSLog(#"Geocode failed with error: %#", error);
return;
}
if (placemarks && placemarks.count > 0)
{
CLPlacemark *placemark = placemarks[0];
NSDictionary *addressDictionary =
placemark.addressDictionary;
NSLog(#"%# ", addressDictionary);
NSString *address = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStreetKey];
NSString *city = [addressDictionary
objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *state = [addressDictionary
objectForKey:(NSString *)kABPersonAddressStateKey];
NSString *zip = [addressDictionary
objectForKey:(NSString *)kABPersonAddressZIPKey];
NSLog(#"%# %# %# %#", address,city, state, zip);
}
}];
Result
{
City = Surat;
Country = India;
CountryCode = IN;
FormattedAddressLines = (
Surat,
Gujarat,
India
);
Name = Surat;
State = Gujarat;
}
2012-12-20 21:33:26.284 CurAddress[4110:11603] (null) Surat Gujarat (null)
I would start with the CLReverseGeocoder class.
This stackoverflow question gets the current city and can probably be adapted for your use.
Following codes can be easy to retrieve full-details.
[geocoder reverseGeocodeLocation:newLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if(placemarks.count){
placeNameLabel.text = [placemarks[0] name];
streetNumberLabel.text = [placemarks[0] subThoroughfare];
streetLabel.text = [placemarks[0] thoroughfare];
neighborhoodLabel.text = [placemarks[0] subLocality];
cityLabel.text = [placemarks[0] locality];
countyLabel.text = [placemarks[0] subAdministrativeArea];
stateLabel.text = [placemarks[0] administrativeArea]; //or province
zipCodeLabel.text = [placemarks[0] postalCode];
countryLabel.text = [placemarks[0] country];
countryCodeLabel.text = [placemarks[0] ISOcountryCode];
inlandWaterLabel.text = [placemarks[0] inlandWater];
oceanLabel.text = [placemarks[0] ocean];
areasOfInterestLabel.text = [placemarks[0] areasOfInterest[0]];
}
}];

Resources