malhobayyeb malhobayyeb - 1 year ago 89
iOS Question

How to detect and change ios app language using Swift?

I want to detect which language the user have for the device. Then I want to change the language to a different language the app will load appropriate images, strings, storyboards.

I used the following to detect the language:

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

However this will return "en" for me even my iOS simulator is set to Arabic language.

Based on Objective-C questions, I tried to do the following to change the language to Arabic:

NSUserDefaults.setValue("ar", forKey: "AppleLanguage")

But this issues an error:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSUserDefaults 0x103daa350> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key AppleLanguage.'

Answer Source

With the code you made, compiler think you're trying to use KVO, setting the value "ar" to the property "AppleLanguage" of the NSUserDefaults class. Which doesn't exist.

Use setObject:forKey: instead of setValue:forKey:

NSUserDefaults.setObject(["ar"], forKey: "AppleLanguage") // First param is an array.

And I never coded in Swift, but don't you need to get the standard defaults NSUserDefaults.standardUserDefaults() before updating anything in it?

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download