美文网首页iOS开发知识小集
iOS判断当前语言环境

iOS判断当前语言环境

作者: 流年划过颜夕 | 来源:发表于2019-04-25 15:59 被阅读109次

公司的SDK打包成静态库后接入测试程序,真机运行发现系统语言环境虽然是简体中文,但是SDK语言环境却是英文。

检测发现,获取当前系统语言的代码如下:

currentLocaleLanguageCode = [[NSLocale currentLocale] objectForKey:NSLocaleLanguageCode];

看似没什么问题,但是真机测试发现了端倪:

在iOS10上运行,返回结果基本与真机语言一致,但是在iOS12上却完全不符合,可见该方法是不可靠的。

查阅了官方源码:

Declaration

@property(class, readonly, copy) NSLocale *currentLocale;

Discussion

The locale is formed from the settings for the current user’s chosen system locale overlaid with any custom settings the user has specified.

Use this property when you need to rely on a consistent locale. A locale instance obtained this way does not change even when the user changes region settings. If you want a locale instance that always reflects the current configuration, use the one provided by the autoupdatingCurrentLocale property instead.

To receive notification of locale changes, add your object as an observer of the a NSCurrentLocaleDidChangeNotification.

可见通过这种方法获得的locale实例即使在用户更改语言区域设置时也不会更改,需要实时依赖通知来监控,明显不符合当前模式。

于是换了种判断方式,获取首选语言顺序,取第一个语言(因为首个语言即为当前系统语言),考虑只支持中文和英文,逻辑如下:

        NSArray *languages = [NSLocale preferredLanguages];
        if (languages.count>0) {
            currentLocaleLanguageCode = languages.firstObject;
            if ([currentLocaleLanguageCode hasPrefix:@"en"]) {
                currentLocaleLanguageCode = @"en";
            }
            else if ([currentLocaleLanguageCode hasPrefix:@"zh"]) {
                currentLocaleLanguageCode = @"zh";
            }
            else {
                currentLocaleLanguageCode = @"en";
            }
        }
        else {
            currentLocaleLanguageCode = @"en";
        }

最后真机运行,再次测试后,结果完美匹配。

相关文章

网友评论

    本文标题:iOS判断当前语言环境

    本文链接:https://www.haomeiwen.com/subject/sujzgqtx.html