-3

I'm trying to get the system language ofrom the iDevice of the user, basically I want 1 image if it'S in french, and another if it's english

any ideas ?

My code (that doesn't display the image either way)

let preferredLanguage = NSLocale.preferredLanguages()[0] as String

if preferredLanguage == "en" {
    navigationItem.titleView = imageView
} else if preferredLanguage == "fr" {
    navigationItem.titleView = imageViewFR
}
ketan
  • 19,129
  • 42
  • 60
  • 98
Jp4Real
  • 1,982
  • 4
  • 18
  • 33
  • What's not working? Also, "uk" is not a valid language. – André Dion Mar 22 '16 at 17:52
  • sorry meant it to show "fr" i corrected it, and the image is not showing. it's the UINavigationBar Title that i'm changing, no IF it's good. With the IF condition it doesn't work – Jp4Real Mar 22 '16 at 17:57
  • 2
    What value are you getting for `preferredLanguage`? – rmaddy Mar 22 '16 at 17:57
  • 3
    *doesn't work* isn't a sufficient description. – vikingosegundo Mar 22 '16 at 17:58
  • the value i'm getting is en-US – Jp4Real Mar 22 '16 at 17:58
  • 1
    NSLocale.preferredLanguages [can return a variety of identifiers](https://developer.apple.com/library/ios/technotes/tn2418/_index.html#//apple_ref/doc/uid/DTS40016588-CH1-LANGUAGE_IDENTIFIERS_IN_IOS_9)... `"en" != "en-US"` – André Dion Mar 22 '16 at 18:00
  • ok, is there anything other than NSLocale I can use ? to put simply I want it to be another image only if the system language is french, else I want it to be then english image – Jp4Real Mar 22 '16 at 18:03
  • 1
    Try getting the `NSLocaleLanguageCode` value from the current locale instead of looking at the list of preferred languages. – rmaddy Mar 22 '16 at 18:04
  • here's my new constant : `let preferredLanguage = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as! String` which returns `en` (in this case) but the code inside the if statement doesn't display – Jp4Real Mar 22 '16 at 18:11

2 Answers2

2

You don't need to write (error-prone) just to localize an image. Just put the image files into the appropriate localization folder in your app bundle — then APIs like NSBundle.pathForResource and UIImage(named:) will automatically load the image corresponding to the user's preferred language. (And if the images for different languages have different dimensions, you don't need separate image views — just use Auto Layout.)

See Localized Resources in Bundles and Adding Additional Resources You Want to Localize in Apple's docs.

rickster
  • 124,678
  • 26
  • 272
  • 326
0

Turns out @rmaddy was right, here's the answer

    let preferredLanguage = NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode) as! String

    if preferredLanguage == "fr" {
        navigationItem.titleView = imageViewFR
    } else {
        navigationItem.titleView = imageView
    }

to get the system language we need to use NSLocale.currentLocale() then it worked ! thanks @rmaddy

Jp4Real
  • 1,982
  • 4
  • 18
  • 33