iOS版:转换ISO阿尔法2阿尔法3国家代码(iOS: Convert ISO Alpha 2 to

2019-09-19 21:29发布

是否有可能以ISO 3166 alpha-2国家代码转换为Alpha 3国家代码的iOS,比如DE到申?

Answer 1:

下面是从α-2的匹配对应关系,以素α3的plist中。 现在,你只需要加载成一个NSDictionnary并在应用程序中使用它。

plist中: 全部转换ISO 3166-1-α-2到ALPHA3



Answer 2:

底座上的答案弗兰克这里是加载plist中,然后转换成3个字母国家ISO代码的代码swift4

plist中: 全部转换ISO 3166-1-α-2到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
    }

}

要使用你只需要:

if let countryCode = CountryUtility.getLocalCountryCode() {

            if let alpha3 = CountryUtility.getCountryCodeAlpha3(countryCodeAlpha2: countryCode){
                print(alpha3) ///result: PRT
            }
        }


文章来源: iOS: Convert ISO Alpha 2 to Alpha 3 country code