如何在 Swift 中以编程方式从字符串文件中获取本地化语言?

How to get Localization languages from strings file programmatically in Swift?

如何在 Swift 和 Xcode 12 中以编程方式获取所有选中的本地化语言?

我想将这些语言放在一个数组中,我可以将其显示为选择器视图,这样用户就可以无缝地更改语言,而无需更改其设备的语言。我想避免对此进行硬编码。

Screenshot of the Localization check boxes in Xcode from my .strings file

这可能会成功:

func localizations() -> [String] {
    guard let contentsURLs = try? FileManager.default.contentsOfDirectory(at: Bundle.main.bundleURL, includingPropertiesForKeys: nil) else { return [] }
    let identifiers = contentsURLs.compactMap { anURL -> String? in
        guard anURL.pathExtension == "lproj" else { return nil }
        return anURL.deletingPathExtension().lastPathComponent
    }

    let humanReadableNames = identifiers.compactMap { anIdentifier in
        return Locale.current.localizedString(forIdentifier: anIdentifier)?.localizedCapitalized
    }

    return humanReadableNames
}

我什至将它们转换为人类可读的语言名称,而不是使用例如“zh-Hans”来表示“中文(简体)”。 当然,如果您自己处理您的语言环境,您可能想使用不同的 Locale.current,但您明白了......