NSLengthFormatter获取stringFromMeters:仅以英里/公里为单位

ZeM*_*oon 5 objective-c ios cllocationdistance

我正在使用NSLengthFormatter类来格式化用户和某个目标之间的距离.

CLLocation *userLocation; //<- Coordinates fetched from CLLocationManager
CLLocation *targetLocation; //<- Some location retrieved from server data

CLLocationDistance distance = [userLocation distanceFromLocation:targetLocation];

NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
NSString *formattedLength = [lengthFormatter stringFromMeters:distance];
Run Code Online (Sandbox Code Playgroud)

现在,如果长度小于1000米,则格式化的距离始终以码或米显示(取决于区域设置).

例如.如果距离= 450.0,格式化的字符串将是492.7码或450米.

如何调整NSLengthFormatter以仅以英里/公里为单位返回距离字符串?

ZeM*_*oon 10

这就是我最终使用的内容:

-(NSString *)formattedDistanceForMeters:(CLLocationDistance)distance
 {
    NSLengthFormatter *lengthFormatter = [NSLengthFormatter new];
    [lengthFormatter.numberFormatter setMaximumFractionDigits:1];

    if ([[[NSLocale currentLocale] objectForKey:NSLocaleUsesMetricSystem] boolValue])
    {
        return [lengthFormatter stringFromValue:distance / 1000 unit:NSLengthFormatterUnitKilometer];
    }
    else
    {
        return [lengthFormatter stringFromValue:distance / 1609.34 unit:NSLengthFormatterUnitMile];
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 很好,谢谢.我恭敬地不同意Sulthan - 在地图应用程序中,我认为你确实想要坚持一个单元,这样用户就不必在头脑中进行转换.这家餐馆距离酒店20英里,距离"0.3英里远" - 不管怎样,都不会出现脚或码.:) (6认同)