首页 > 解决方案 > 如何使用 Swift 在 iOS 上获取 ISO 639-2 国家代码

问题描述

目前我使用了以下代码,但它只会返回两位数的代码

    if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
      print("Code => \(countryCode)") //FR
    }

但我需要三位数代码 (FRA),请有人建议我获取 ISO

639-2 代码

我也检查了 Apple 文档,但我不知道如何获得确切的代码

在此处输入图像描述

https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPInternational/LanguageandLocaleIDs/LanguageandLocaleIDs.html#//apple_ref/doc/uid/10000171i-CH15

谢谢你。

标签: iosiphoneswiftswift3swift2

解决方案


在https://github.com/almerlucke/NSLocale-ISO639_2提供了一个 Objective C 解决方案。

使用https://github.com/almerlucke/NSLocale-ISO639_2/blob/master/Resources/iso639_2.bundle/iso639_1_to_iso639_2.plist创建自己的加载并不难

public extension Locale {

    private static let allIso639_2LanguageIdentifiers: [String: String] = {
        guard let path = Bundle.main.path(forResource: "iso639_1_to_iso639_2", ofType: "plist") else { return [:] }
        guard let result = NSDictionary(contentsOfFile: path) as? [String: String] else { return [:] }

        return result
    }()

    public var iso639_2LanguageCode: String? {
        guard let languageCode = languageCode else { return nil }
        return Locale.allIso639_2LanguageIdentifiers[languageCode]
    }

}

推荐阅读