I got an application which use GPS and display actual location on some labels. Here is the method for updating location:
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.longitude];
latitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.latitude];
}
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
[address sizeToFit];
NSArray *locationArray = [[NSArray alloc] initWithObjects:placemark.thoroughfare,placemark.subThoroughfare,
placemark.postalCode,placemark.locality,placemark.country, nil];
address.text = [NSString stringWithFormat:@"%@, %@\n%@ %@\n%@",
[locationArray objectAtIndex:0],
[locationArray objectAtIndex:1],
[locationArray objectAtIndex:2],
[locationArray objectAtIndex:3],
[locationArray objectAtIndex:4]];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
Now, sometimes some objects of 'locationArray' are 'null', and the relative labels show me '(null)' on the application, which is not so nice. So I need an 'if' cycle that would check if an object of 'locationArray' is 'null' and, if it is, will not be showed. Any ideas?
UPDATE
I resolved the issue removing the array and using @trojanfoe's method (slightly modified). Here is the code:
- (NSString *)sanitizedDescription:(NSString *)obj {
if (obj == nil)
{
return @"";
}
return obj;
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
//NSLog(@"didUpdateToLocation: %@", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
longitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.longitude];
latitude.text = [NSString stringWithFormat:@"%.3f", currentLocation.coordinate.latitude];
}
NSLog(@"Resolving the Address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
//NSLog(@"Found placemarks: %@, error: %@", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
[address sizeToFit];
address.text = [NSString stringWithFormat:@"%@, %@\n%@ %@\n%@",
[self sanitizedDescription:placemark.thoroughfare],
[self sanitizedDescription:placemark.subThoroughfare],
[self sanitizedDescription:placemark.postalCode],
[self sanitizedDescription:placemark.locality],
[self sanitizedDescription:placemark.country]];
} else {
NSLog(@"%@", error.debugDescription);
}
} ];
}
Thank you so much to all for helping :)