Can't get if then statement to work? [duplicate] - ios

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
xcode iOS compare strings
Trying to get a UIImageview to show a different image based on the location (city) of the user, here is the code I got:
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
//Display country and city
country.text = [NSString stringWithFormat:placemark.country];
city.text = [NSString stringWithFormat:placemark.locality];
if (placemark.locality==#"Cupertino")
banner.image = [UIImage imageNamed:#"cupertino.png"];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
I can get the labels to display the country and city, but can't get the UIImageview to change based on the city, any ideas?

Use isEqualToString: method to compare the string, like
if ([placemark.locality isEqualToString:#"Cupertino"])
banner.image = [UIImage imageNamed:#"cupertino.png"];
} else {
NSLog(#"%#", error.debugDescription);
}

Make sure you have allocated the image using [UIImage alloc] ..

Related

Sign Up + Confirmation Password iOS [duplicate]

This question already has answers here:
Understanding NSString comparison
(7 answers)
Closed 7 years ago.
I´m trying to make a registration form. There are two UITextField to write the Password and to confirm it. When i write exactly the same password, it always shows: "Passwords do not match ".
-(IBAction)signUp:(id)sender{
#try {
if([[name text] isEqualToString:#""] || [[mail text] isEqualToString:#""] || [[phone text] isEqualToString:#""] || [[password text] isEqualToString:#""] || [[rpassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please check every field" :#"¡Alert!"];
}else if (password.text!=rpassword.text){
[self alertStatus:#"Passwords do not match " :#"¡Please Check!"];
}else {
NSString *strURL = [NSString stringWithFormat:#"http://miwebsite.com/signup.php?var1=%#&var2=%#&var3=%#&var4=%#", name.text, mail.text, phone.text, password.text];
NSURL *url2 = [NSURL URLWithString:strURL];
NSLog(#"url: %#", url2);
NSError *error;
NSData *dataURL = [NSData dataWithContentsOfURL:url2 options:0 error:&error];
if (dataURL == nil) {
NSLog(#"error: %#", error);
}
else {
NSLog(#"dataURL: %#", dataURL);
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
// THE REST OF THE CODE GOES HERE...
}
}
} #catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sorry." :#"Failed"];
}
}
I used the debugger. password.text and rpassword.text are exactly the same word. ¿Why my code goes inside that sentence?
Thanks in advanced.
== in objective C is a pointer comparison instead of the content comparison. The text NSString object have 2 different memory address or pointers associated to them and although the content is same the memory they point is different and hence the statement inside this
else if (password.text!=rpassword.text){
[self alertStatus:#"Passwords do not match " :#"¡Please Check!"];
}
is executed. The pointers are different.
What you need is string comparison by doing so:
else if (![password.text.isEqualToString:rpassword.text]){
[self alertStatus:#"Passwords do not match " :#"¡Please Check!"];
}
For more explanation please check this link:
Understanding NSString comparison

Objective-C get variable out of block

I'm struggling with getting a variable out of a block. Seems to be a pretty basic thing but I can't figure it out! How can I access it? e.g. usercity out of the block? Usercity is declared as NSString in .h.
[ceo reverseGeocodeLocation: loc completionHandler:
^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//NSLog(#"placemark %#",placemark);
//String to hold address
//NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//NSLog(#"addressDictionary %#", placemark.addressDictionary);
//NSLog(#"placemark %#",placemark.region);
NSLog(#"Land %#",placemark.country); // Give Country Name
NSLog(#"City %#",placemark.locality); // Extract the city name
NSLog(#"Adresse %#",placemark.name);
//NSLog(#"location %#",placemark.ocean);
NSLog(#"Zip %#",placemark.postalCode); //ZipCode
NSLog(#"sonstiges %#",placemark.subLocality);
//Save values in variables
usercountry = placemark.country;
usercity = placemark.locality;
userzip = placemark.postalCode;
NSLog(#"usercity: %#",usercity);
//NSLog(#"location %#",placemark.location);
}
];
Is this what you're looking for?
__block NSString *userCity;
[ceo reverseGeocodeLocation: loc completionHandler:^(NSArray *placemarks, NSError *error) {
CLPlacemark *placemark = [placemarks objectAtIndex:0];
...
userCity = placemark.locality;
}];
But if you want to actually be able to check its value outside of the block, you'll have to do so after the completion handler updates the value. Perhaps make it a property, ie. self.userCity?
Your code in the block has to store usercity where you want it. You can't "get something out" of a block, the code in the block has to do it.
You do know that a block can access all variables in the surrounding method, don't you?

Insert Latitude and Longitude Programmatically for Reverse Geolocation

I have a Situation ,where i am pulling the Latitude and Longitude from a XML file ,Parsing and Displaying it .and i am successfully be able to Do it in Two Different UILabels .but now i need to the Location and Display it in a Label.Can someone suggest me how to achieve that , i have this code , but its only let me to select the Value of Coordinates from Simulator only .
- (IBAction)geoCodeLocation:(id)sender{
//Geocoding Block
[self.geoCoder reverseGeocodeLocation: locationManager.location completionHandler:
^(NSArray *placemarks, NSError *error) {
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
NSString *locatedAt = [[placemark.addressDictionary valueForKey:#"FormattedAddressLines"] componentsJoinedByString:#", "];
//Print the location to console
NSLog(#"I am currently at %#",locatedAt);
//Set the label text to current location
[locationLabel setText:locatedAt];
}];
}
Suggestion : this Question is not about XML parsing .
Try This
CLLocation *location = [[CLLocation alloc] initWithLatitude:37.78583400 longitude:-122.40641700];
[self.geoCoder reverseGeocodeLocation: location completionHandler:
^(NSArray *placemarks, NSError *error) {
//Get nearby address
CLPlacemark *placemark = [placemarks objectAtIndex:0];
//String to hold address
locatedAtcountry = placemark.country;
locatedAtcity = placemark.locality;
locatedAtisocountry = placemark.ISOcountryCode;
//Print the location to console
NSLog(#"Estas en %#",locatedAtcountry);
NSLog(#"Estas en %#",locatedAtcity);
NSLog(#"Estas en %#",locatedAtisocountry);
[cityLabel setText:[NSString stringWithFormat:#"%#",locatedAtcity]];
[locationLabel setText:[NSString stringWithFormat:#"%#",locatedAtcountry]];
//Set the label text to current location
//[locationLabel setText:locatedAt];
}];

Get current city and country from CLGeocoder?

I've been all over the internet trying to find out how to get the city and country from CLGeocoder. I can get the longitude and latitude easily but I need the city and country information, and I keep running into deprecated methods and such, any ideas? It basically needs to get the location, then have an NSString for the country, and an NSString for the city, so I can use them to look up more info or put them on labels, etc.
You need to revise your terminology a bit - CLGeocoder (and most geocoders) won't give you a 'city' per-se - it uses terms such as 'Administrative Area', 'Subadministrative Area', etc. The CLGeocoder object will return an array of CLPlacemark objects which you can then query for the information you need. You init a CLGeocoder and call the reverseGeocodeLocation function with a location and a completion block. Here's an example:
if (osVersion() >= 5.0){
CLGeocoder *reverseGeocoder = [[CLGeocoder alloc] init];
[reverseGeocoder reverseGeocodeLocation:self.currentLocation completionHandler:^(NSArray *placemarks, NSError *error)
{
DDLogVerbose(#"reverseGeocodeLocation:completionHandler: Completion Handler called!");
if (error){
DDLogError(#"Geocode failed with error: %#", error);
return;
}
DDLogVerbose(#"Received placemarks: %#", placemarks);
CLPlacemark *myPlacemark = [placemarks objectAtIndex:0];
NSString *countryCode = myPlacemark.ISOcountryCode;
NSString *countryName = myPlacemark.country;
DDLogVerbose(#"My country code: %# and countryName: %#", countryCode, countryName);
}];
}
Now note that the CLPlacemark doesn't have a 'city' property. The full list of properties can be found here: CLPlacemark Class Reference
You can get city, country and iso country code using this (Swift 5):
private func getAddress(from coordinates: CLLocation) {
CLGeocoder().reverseGeocodeLocation(coordinates) { placemark, error in
guard error == nil,
let placemark = placemark
else
{
// TODO: Handle error
return
}
if placemark.count > 0 {
let place = placemark[0]
let city = place.locality
let country = place.country
let countryIsoCode = place.isoCountryCode
}
}
}

Error when assigning NSString variable in a block

- (NSString *) geocodeAddressFromCoordinate:(CLLocationCoordinate2D)coordinate
{
CLLocation *location = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
__block NSMutableString * address = [NSMutableString string];
geocoder = [[CLGeocoder alloc]init];
[geocoder reverseGeocodeLocation:location completionHandler:^(NSArray *placemarks, NSError *error)
{
if (error) {
NSLog(#"%#", [error localizedDescription]);
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"No results were found" message:#"Try another search" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
alert.show;
return;
}
if ([placemarks count]>0)
{
NSLog([placemarks description]);
CLPlacemark *placemark = [placemarks objectAtIndex:0];
NSLog(placemark.locality);
//This line makes an error
[address initWithString:placemark.locality];**
}
}];
return address;
}
Got following runtime error:
* Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* initialization method
-initWithCharactersNoCopy:length:freeWhenDone: cannot be sent to an abstract object of class __NSCFString: Create a concrete instance!'
You should never call 'initWithString:' without a matching alloc. Looks more like what you want is [address setString:placemark.locality]
You have already initialized address with this line [NSMutableString string]; so your call to [address initWithString:placemark.locality]; is trying to initialize an already initialized object.
Change this:
[address initWithString:placemark.locality];
To:
[address setString:placemark.locality];
NSString Class Reference
NSMutableString Class Reference
[address initWithString:placemark.locality];
should be something more like:
address = placemark.locality;
or
[address appendString:placemark.locality];
depending on what yu are trying to accomplish.
At this point, your string is already initialized, [NSMutableString string] is a convenience method which essential returns [[[NSMutableString alloc] init] autorelease]. You are trying to re init an already inited object, which is bad.
Change that line to [address appendString:placemark.locality];

Resources