Search code examples
iosobjective-ccllocationdistance

NSLengthFormatter get stringFromMeters: in miles/kilometers only


I am using the NSLengthFormatter class to format the distance between the user and some destination.

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];

Now, if the length is less than 1000 meters, the formatted distance is always shown in yards or meters (depending on the locale).

Eg. if distance = 450.0, the formatted string will be 492.7 yd or 450 m.

How can I tweak NSLengthFormatter to return the distance strings in miles/kilometers only?


Solution

  • This is what I have ended up using:

    -(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];
        }
    }
    

    EDIT:

    The same in Swift would look like:

    func formattedDistanceForMeters(distance:CLLocationDistance) -> String {
            let lengthFormatter:NSLengthFormatter! = NSLengthFormatter()
            lengthFormatter.numberFormatter.maximumFractionDigits = 1
    
            if NSLocale.currentLocale().objectForKey(NSLocaleUsesMetricSystem).boolValue()
            {
                return lengthFormatter.stringFromValue(distance / 1000, unit:NSLengthFormatterUnitKilometer)
            }
            else
            {
                return lengthFormatter.stringFromValue(distance / 1609.34, unit:NSLengthFormatterUnitMile)
            }
        }