Search code examples
iosobjective-ccllocationmanagercllocation

Make address lines blank if they don't exist (Objective-C)


My app finds the user's location, and shows the address in a label. The problem is that if something doesn't exist at a certain place, a postal code for example, then the line says (null). How do I make that line blank? I suppose it has to be set to nil somehow, somewhere...

Please help!

Here's my code:

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {

NSLog(@"Location: %@", newLocation);
CLLocation *currentLocation = newLocation;

[geoCoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {

    if (error == nil && [placemarks count] > 0) {

        placeMark = [placemarks lastObject];

        NSString *locationString = [NSString stringWithFormat:@"%@ %@\n%@ %@\n%@\n%@",
                                    placeMark.subThoroughfare,
                                    placeMark.thoroughfare,
                                    placeMark.postalCode,
                                    placeMark.locality,
                                    placeMark.administrativeArea,
                                    placeMark.country];

        locationLabel.text = locationString;

    }

    else {

        NSLog(@"%@", error.debugDescription);

    }

}];

}

Solution

  • Quick and (very) dirty solution, but ones may find it readable:

    substitute placeMark.postalCode,

    with

    placeMark.postalCode ? placeMark.postalCode : @"",
    

    for each element you want nothing (or whatever other string) to appear in case of nil.

    Or just write custom code to check for each element in local variables.

    --

    Edit: In the remote case that you actually have a string containing "(null)" the you may want to consider checking for this value substituting again each line with:

    [placeMark.postalCode isEqualToString:@"(null)"]? @"" : placeMark.postalCode,
    

    consider anyway that you should really take care of this earlier in your logic, probably some parsing went wrong when creating the placeMark object string members.