Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current language code with Swift?

Tags:

swift

nslocale

People also ask

How do I get the current language code in Swift?

if let currentLanguage = Locale. currentLanguage { print(currentLanguage. rawValue) // Your code here. }

How do I find current device language?

You can use Locale. getDefault(). getLanguage(); to get the usual language code (e.g. "de", "en").

What is locale in Swift?

Information about linguistic, cultural, and technological conventions for use in formatting data for presentation.

What type of language is Swift?

The Swift programming language is a general-purpose, open-source programming language designed by Apple. The language is influenced by Python, making it fast and intuitive. Swift is mainly used for native iOS and macOS development. Many popular apps including LinkedIn, Lyft, and WordPress are written in Swift.


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]

Swift 4 & 5:

Locale.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.


In Swift 3:

NSLocale.current.languageCode

To get current language used in your app (different than preferred languages)

NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)!

swift 3

let preferredLanguage = Locale.preferredLanguages[0] as String
print (preferredLanguage) //en-US

let arr = preferredLanguage.components(separatedBy: "-")
let deviceLanguage = arr.first
print (deviceLanguage) //en