如何以编程方式访问 iOS 13 中的应用程序语言?

How to programmatically access the apps language in iOS 13?

Starting from iOS 13 Apple 允许:

Language selection per app

Use third‑party apps in a different language from your system language.

正如我在我的应用程序设置页面的“设置”应用程序中看到的那样,有一个新的“首选语言”条目显示了我的应用程序的本地化语言选择。

来自 Facebook 的示例:

Image source


我能否以编程方式访问所选语言的值?

如果是用哪个键?

[[NSUserDefaults standardUserDefaults] objectForKey:@"key???"];

我认为你正在努力达到 "Locale.current.languageCode"

您可以尝试使用以下代码获取应用程序首选语言。

let appLang = Locale.preferredLanguages[0]

我通常添加这个小扩展:

public extension Locale {
    /// Returns the prefered locale used in the app, if none is found, returns `Locale.current`
    static var appCurrent : Locale {
        if let prefered = Bundle.main.preferredLocalizations.first {
            return Locale(identifier: prefered)
        }
        else {
            return current
        }
    }
}

然后就可以用Locale.appCurrent找回了。

NOTE: I use Bundle.preferedLocalizations instead of Locale.preferedLocale because it returns the real app language. For instance, if your phone is in French and your app is only localized in English, the Bundle.preferedLocalizations will return en, because this is the Locale your app runs in. The Locale.preferedLocale will return French but all other localizations will be in English, because your app runs in English on a French device.

编辑:这是Objective-C版本。

@interface NSLocale(AppCurrent)

+ (NSLocale *) appCurrent;

@end

@implementation NSLocale(AppCurrent)

+ (NSLocale *) appCurrent {
    NSString * prefered = [[[NSBundle mainBundle] preferredLocalizations] firstObject];
    if (prefered != nil) {
        return [[NSLocale alloc] initWithLocaleIdentifier:prefered];
    }
    else {
        return [NSLocale currentLocale];
    }
}

@end

然后,这样称呼它:[NSLocale appCurrent]

要检测设备语言,您可以使用:

let locale = Locale.current.languageCode

获取设备语言:

let locale = NSLocale.current.languageCode

获取应用程序语言

let appLang = Locale.preferredLanguages[0]