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

标签 ios country-codes

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

最佳答案

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

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
    }

}

要使用你只需要:

if let countryCode = CountryUtility.getLocalCountryCode() {

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

关于iOS:将 ISO Alpha 2 转换为 Alpha 3 国家代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11576947/

相关文章:

ios - 将对象添加到 NSMutableArray - 奇怪的行为

android - 我怎样才能得到国家(或其 ISO 代码)?

python - 从用户输入中使用 pycountry 获取国家代码

angularjs - angularJs 的国家选择控件

javascript - 如何引导中国游客到优酷,其他人到Youtube?

Ios 7 自定义 UINavigationController 动画因目标 Controller 中的 mapView 而失败

ios - Swift - 不检测在自定义单元格中移动 slider 的事件

ios - 谷歌API PHP : Wrong audience in jwt for iOS only

ios - 增加 1 UITableViewCell 分隔符高度