Locale.current reporting wrong language on device

2019-05-07 08:27发布

问题:

I'm trying to format currency values in an iOS app, and I'm using the current Locale settings on the device to use the appropriate currency formatting.

In the simulator, everything seems to run fine: when using currencyFormatter.locale = Locale.current, it takes the right locale settings and prints numbers with the right currency format.

On my iPhone however, which is configured in French with French regional settings, I would expect another format to be used (e.g.: 1 234,56 €). But it does not work, and seems to use an English formatting style (e.g.: €1 234,56).

In fact, if I print the current Locale from my app on the device, it does not return fr_FR as I would expect:

NSLog(Locale.current.identifier)
>>> en_FR

The region is good but the language is not, though iOS on that device is clearly in French.

Has anyone an idea about this?

Thanks!

回答1:

Based on @Romain's answer the forced unwrapping of first! could be avoided by using the Locale.current.identifier as fallback.

func getPreferredLocale() -> Locale {
    guard let preferredIdentifier = Locale.preferredLanguages.first else {
        return Locale.current
    }
    return Locale(identifier: preferredIdentifier)
}


回答2:

@florieger's answer in the form of extension:

import Foundation

extension Locale {
    static func preferredLocale() -> Locale {
        guard let preferredIdentifier = Locale.preferredLanguages.first else {
            return Locale.current
        }
        return Locale(identifier: preferredIdentifier)
    }
}

Then use it like this:

dateFormatter.locale = Locale.preferredLocale()
datePicker.locale = Locale.preferredLocale()


回答3:

Following @MartinR's hint, I'm now using currencyFormatter.locale = Locale(identifier: Locale.preferredLanguages.first!), which corresponds exactly to the device's current language & region settings.

I'm not entirely sure this code is bullet-proof though (because of first!, most notably) so if you have other suggestions, please feel free.