Getting current device language in iOS?

前端 未结 30 2731
星月不相逢
星月不相逢 2020-11-22 09:10

I\'d like to show the current language that the device UI is using. What code would I use?

I want this as an NSString in fully spelled out format. (Not

30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-22 09:32

    As of iOS 9, if you just want the language code without country code, you'll want this sort of helper function - since the language will contain the country code.

    // gets the language code without country code in uppercase format, i.e. EN or DE
    NSString* GetLanguageCode()
    {
        static dispatch_once_t onceToken;
        static NSString* lang;
        dispatch_once(&onceToken, ^
        {
            lang = [[[NSLocale preferredLanguages] objectAtIndex:0] uppercaseString];
            NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:@"^[A-Za-z]+" options:0 error:nil];
            NSTextCheckingResult* match = [regex firstMatchInString:lang options:0 range:NSMakeRange(0, lang.length)];
            if (match.range.location != NSNotFound)
            {
                lang = [lang substringToIndex:match.range.length];
            }
        });
        return lang;
    }
    

提交回复
热议问题