preferredLanguages iOS 9

ぐ巨炮叔叔 提交于 2019-11-28 12:50:41

If language is returning other values such a "fr-FR" and "fr-CA", then you should split language on the - character. This will work even you simply get "fr".

NSString *firstLanguage = [[NSLocale preferredLanguages] firstObject];
NSString *language = [[firstLanguage componentsSeparatedByString:@"-"] firstObject];
if ([language isEqualToString:@"fr"]) {
} else {
}

Hey there Don't do like that It will create issue when localization are set different for language having different regions as like es-mx and es-cl. In that case above solution will create issue. Use following code for the solution:

NSString *selectedLanguage = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];

In case your have selected zh-Hans-US from setting But your app is having zh-Hans-TW and zh-Hans-CN only. That the above code will return you "zh-Hans-TW" the first preferred Localization.

Try this may be useful to you.

You shouldn't split the NSLocale. NSLocale has some Keys, which you can retrieve with objectForKey:

In your example you can write the following:

[[[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode]
            isEqualToString:@"fr"]

[NSLocale currentLocale] is actually the same as [[NSLocale preferredLanguages] firstObject] but has some additional information where you can retrieve which decimal separator should be used or which currency symbol.

Other relevant Keys can be found in the class reference from apple.

Paste my codes in here, maybe help you

- (NSString *)localizedStringForKey:(NSString *)key withDefault:(NSString *)defaultString
{
    static NSBundle *bundle = nil;
    if (bundle == nil)
    {
        NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"your_resources" ofType:@"bundle"];
        bundle = [NSBundle bundleWithPath:bundlePath] ?: [NSBundle mainBundle];
        //manually select the desired lproj folder
        for (NSString *language in [NSLocale preferredLanguages])
        {
            for (NSString *loc in [bundle localizations] ) {
                if ([language hasPrefix:loc])
                {
                    bundlePath = [bundle pathForResource:loc ofType:@"lproj"];
                    bundle = [NSBundle bundleWithPath:bundlePath];
                    goto getString;
                }
            }
        }
    }
getString:
    defaultString = [bundle localizedStringForKey:key value:defaultString table:nil];
    return [[NSBundle mainBundle] localizedStringForKey:key value:defaultString table:nil];
}

My fix on my code is simple :

NSString *language = [[NSLocale preferredLanguages] objectAtIndex:0];
NSRange range = [language rangeOfString:@"-" options:NSBackwardsSearch];
NSString * languageMark = [language substringToIndex:range.location];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!