I want get the language code of the device (en, es...) in my app written with Swift. How can get this?
I\'m trying this:
var preferredLanguages : NSL
Swift 5.3:
let languagePrefix = Locale.preferredLanguages[0]
print(languagePrefix)
In Swift 3
let langStr = Locale.current.languageCode
It's important to make the difference between the App language and the device locale language (The code below is in Swift 3)
Will return the Device language:
let locale = NSLocale.current.languageCode
Will return the App language:
let pre = Locale.preferredLanguages[0]
you may use the below code it works fine with swift 3
var preferredLanguage : String = Bundle.main.preferredLocalizations.first!
In Swift 3:
NSLocale.current.languageCode
Swift 3 & 4 & 4.2 & 5
Locale.current.languageCode
does not compile regularly. Because you did not implemented localization for your project.
You have two possible solutions
1) String(Locale.preferredLanguages[0].prefix(2))
It returns phone lang properly.
If you want to get the type en-En
, you can use Locale.preferredLanguages[0]
2)
Select Project(MyApp)
->Project (not Target)
-> press + button into Localizations
, then add language which you want.