Locale.current reporting wrong language on device

走远了吗. 提交于 2019-12-03 13:20:12
florieger

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)
}
wzbozon

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

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.

@Romain The problem here is that you have not localized your app for French but only for English.

Go to the upper left blue file with the name of your app, select Project > Info and in the Localization area you will see "English - Development Language". Press + and choose French (fr).

That's it. Now you can use Locale.current and if the first language of a device (or simulator) is French, your app will show French currency format.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!