iOS:将ISO Alpha 2转换为Alpha 3国家/地区代码

Kot*_*teg 4 country-codes ios

是否可以将ISO 3166 alpha-2国家/地区代码转换为iOS中的alpha 3国家/地区代码,例如DE到DEU?

小智 13

这是从Alpha2到alpha3的匹配对应的plist.现在您只需将其加载到NSDictionnary并在您的应用程序中使用它.

plist:完全转换ISO 3166-1-Alpha2到Alpha3

  • 任何在2017年发现这一点的人,请注意该列表并不完整.有些国家失踪了. (2认同)

Tia*_*des 5

基于 Franck 的答案,这里是用于加载 plist 的代码 swift4,然后转换 3 个字母的国家/地区 ISO 代码

plist:将 ISO 3166-1-Alpha2 完全转换为 Alpha3

//
//  CountryUtility.swift
//

import Foundation

struct CountryUtility {


    static private func loadCountryListISO() -> Dictionary<String, String>? {

        let pListFileURL = Bundle.main.url(forResource: "iso3166_2_to_iso3166_3", withExtension: "plist", subdirectory: "")
        if let pListPath = pListFileURL?.path,
            let pListData = FileManager.default.contents(atPath: pListPath) {
            do {
                let pListObject = try PropertyListSerialization.propertyList(from: pListData, options:PropertyListSerialization.ReadOptions(), format:nil)

                guard let pListDict = pListObject as? Dictionary<String, String> else {
                    return nil
                }

                return pListDict
            } catch {
                print("Error reading regions plist file: \(error)")
                return nil
            }
        }
        return nil
    }


    /// Convertion ISO 3166-1-Alpha2 to Alpha3
    /// Country code of 2 letters to 3 letters code
    /// E.g: PT to PRT
    static func getCountryCodeAlpha3(countryCodeAlpha2: String) -> String? {

        guard let countryList = CountryUtility.loadCountryListISO() else {
            return nil
        }

        if let countryCodeAlpha3 = countryList[countryCodeAlpha2]{
            return countryCodeAlpha3
        }
        return nil
    }


    static func getLocalCountryCode() -> String?{

        guard let countryCode = NSLocale.current.regionCode else { return nil }
        return countryCode
    }


    /// This function will get full country name based on the phone Locale
    /// E.g. Portugal
    static func getLocalCountry() -> String?{

        let countryLocale = NSLocale.current
        guard let countryCode = countryLocale.regionCode else { return nil }
        let country = (countryLocale as NSLocale).displayName(forKey: NSLocale.Key.countryCode, value: countryCode)
        return country
    }

}
Run Code Online (Sandbox Code Playgroud)

要使用您只需要:

if let countryCode = CountryUtility.getLocalCountryCode() {

            if let alpha3 = CountryUtility.getCountryCodeAlpha3(countryCodeAlpha2: countryCode){
                print(alpha3) ///result: PRT
            }
        }
Run Code Online (Sandbox Code Playgroud)