NSLocale preferredLanguages changes in iOS 9

With iOS 9, the results returned by NSLocale.preferredLanguages() can differ from iOS8. In iOS 8 and earlier, only certain language, script, and region combinations were returned by this API.

In iOS 9 Apple introduced some changes at how NSLocale +preferredLanguagesreturns languages. It returns strings like en-US, ru-RU instead of en, ru as it used to.

When getting the current language of the device, we usually use the following API:

[NSLocale preferredLanguages]

In iOS 8 and below, the above API will returns an NSArray of language code.

For example:
“en”, “ja”, “es”

But in iOS 9, this changed! So if you are using this API in your code, you need to consider the new return value format. The return values are now in the format:

“<language code>-<region code>”

Solution for iOS 9:

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0]; //==> language = "en-US"
NSDictionary *languageDic = [NSLocale componentsFromLocaleIdentifier:language];
NSString *countryCode = [languageDic objectForKey:@"kCFLocaleCountryCodeKey"]; //==>countryCode = "US"
NSString *languageCode = [languageDic objectForKey:@"kCFLocaleLanguageCodeKey"]; //==> languageCode = "en"