Get iOS current language (including country code)

2019-04-05 09:16发布

I need to get a string like en_US or es_ES in iOS.

The obvious method is to use [NSLocale currentLocale] and get the language info from there. However, that gives you the "region format" and not the actual device language, which means that if you have the device language in english but the region format as "spain", it'll erroneously report es_ES.

If you need the device language you must do this instead: [[NSLocale preferredLanguages] objectAtIndex:0]

However, that only gives you the language, so you get something like en or es, without the country code at the end.

How would I get the country code correctly, like Safari does?

7条回答
Animai°情兽
2楼-- · 2019-04-05 10:20

An alternative would be to reconstruct the locale from the components of the current locale, swapping in the language that you want.

For example, to get the current locale but modified to use the language which UIKit is currently using to display the app:

let languageCode = Bundle.main.preferredLocalizations.first ?? "en"
var components = Locale.components(fromIdentifier: Locale.current.identifier)
components[NSLocale.Key.languageCode.rawValue] = languageCode
let locale = Locale(identifier: Locale.identifier(fromComponents: components))
查看更多
登录 后发表回答