NSLocale currentLocale always returns “en_US” not user's current language

后端 未结 9 1705
夕颜
夕颜 2020-11-30 21:28

I\'m in the processes of internationalizing an iPhone app - I need to make programmatic changes to certain views based on what the user\'s current locale is. I\'m going nut

9条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-30 21:44

    Question is too old, but this code may help to many:

    The main.m should look like this:

        NSString *localecode=[[NSLocale currentLocale] localeIdentifier];
        localecode=[localecode substringToIndex:2]; //en_GB -> en
        NSArray *arr = [NSLocale preferredLanguages];
        NSMutableArray * mutable = [arr mutableCopy];
        NSString *prefered = [mutable firstObject];
        if(![localecode isEqualToString:prefered]){
            if(![prefered isEqualToString:@"es"] && ![prefered isEqualToString:@"en"] && ![prefered isEqualToString:@"pt"]){
                int index = [mutable indexOfObject:@"en"];
                [mutable replaceObjectAtIndex:0 withObject:@"en"];
                [mutable replaceObjectAtIndex:index withObject:prefered];
                [[NSUserDefaults standardUserDefaults] setObject:mutable forKey:@"AppleLanguages"];
    
            }
            else{
                int index = [mutable indexOfObject:localecode];
                [mutable replaceObjectAtIndex:0 withObject:localecode];
                [mutable replaceObjectAtIndex:index withObject:prefered];
                [[NSUserDefaults standardUserDefaults] setObject:mutable forKey:@"AppleLanguages"];
            }
        }
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
    

    What do this? If the current language of the device es Spanish, English or Portuguese use the the application uses the localized strings, by the other hand if the current language is not one of those and is not supported by application is set to English.

提交回复
热议问题