ios - 如果地址行不存在则将其设为空白(Objective-C)

标签 ios objective-c cllocationmanager cllocation

我的应用找到用户的位置,并在标签中显示地址。问题是如果某个地方不存在某些东西,例如邮政编码,那么该行会显示 (null)。我如何使该行空白?我想它必须以某种方式在某处设置为 nil...

请帮忙!

这是我的代码:

- (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);

    }

}];

}

最佳答案

此代码检查所有字段是否为 nil(这会导致 <null> 输出)并替换 nil带有空字符串的值。

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

关于ios - 如果地址行不存在则将其设为空白(Objective-C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33350567/

相关文章:

ios - UIButton 在 UIScrollView 中不工作/不可点击

php - 使用 IOS 解析基本的 JSON

ios - 是否可以检测 facebook/gmail 横幅/警报通知

iphone - uiview 在 ios7 中出现失真,但适用于 ios6 和其他

ios - 有没有办法使用内置的苹果 API 在 mkmapview 中获取方向?

ios - UICollectionView 无法滚动查看整个最后一行

ios - 位置管理器委托(delegate)调用更新 TableView 问题

ios - 在 iPhone 上创建全景图的最佳方式?

swift - 将 CLLocation Manager 值存储在设备 swift 中

swift - locationManager 未被识别为类变量