2

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

2 Answers 2

2

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?

Sign up to request clarification or add additional context in comments.

2 Comments

setObject is better but setValue would work as well. Your second point solves the problem.
Did not work for me. The app did not change to RTL and when rerun the app the language returned by NSLocale.preferredLanguages()[0] is always "en-US"
0

To answer the question about detecting the current language on the device is

NSLocale.currentLocale().objectForKey(NSLocaleLanguageCode)! as! String

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.