Language check in iOS app

Task: I have two UIImageViews, and I want to represent ImageView1 if the system language is Ukrainian, and if it is not Ukrainian (English / Polish, etc.), I want to introduce ImageView2.

I tried:

println(NSUserDefaults.standardUserDefaults().objectForKey("AppleLanguages")) 

but this code only provides a list of available languages. I also tried

 var language: AnyObject? = NSLocale.preferredLanguages().first 

but how can I compare this variable with English or Ukrainian?

+6
source share
3 answers

Swift 3 You can take the language code as follows

 let preferredLanguage = NSLocale.preferredLanguages[0] 

And then you need to compare it with a code string

 if preferredLanguage == "en" { print("this is English") } else if preferredLanguage == "uk" { print("this is Ukrainian") } 

You can find the codes here.

French language test example ...

 /// Is Device use french language /// Consider, "fr-CA", "fr-FR", "fr-CH" et cetera /// /// - Returns: Bool static func isFrench() -> Bool { return NSLocale.preferredLanguages[0].range(of:"fr") != nil } 
+18
source

you can use the code below it works fine with speed 3

  if Bundle.main.preferredLocalizations.first == "en" { print("this is english") }else{ print("this not english") } 
+1
source

Swift 4 If you have more languages ​​in the queue (the preferred language will be returned: "uk-US", for example), but you want it first.
You can do it as follows:

 let preferredLanguage = NSLocale.preferredLanguages[0] if preferredLanguage.starts(with: "uk"){ print("this is Ukrainian") } else{ print("this is not Ukrainian") } 
0
source

Source: https://habr.com/ru/post/984097/


All Articles