iOS: Convert ISO Alpha 2 to Alpha 3 country code

我只是一个虾纸丫 提交于 2020-01-13 13:04:43

问题


Is it possible to convert ISO 3166 alpha-2 country code to alpha 3 country code in iOS, for instance DE to DEU?


回答1:


Here is a plist of the matching correspondance from Alpha2 to alpha3. Now you just have to load that up into a NSDictionnary and use it in your app.

The plist : Full conversion ISO 3166-1-Alpha2 to Alpha3




回答2:


Base on the answer Franck here is the code swift4 for loading the plist and then to convert 3 letters Country ISO code

The plist: Full conversion ISO 3166-1-Alpha2 to 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
    }

}

To use you just need to:

if let countryCode = CountryUtility.getLocalCountryCode() {

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


来源:https://stackoverflow.com/questions/11576947/ios-convert-iso-alpha-2-to-alpha-3-country-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!