How do I get a list of countries in Swift ios?

后端 未结 12 1608
日久生厌
日久生厌 2021-02-05 03:29

I\'ve already seen two similar questions to mine, but the answers for those questions do not work for me. I have an old project with a list of countries manually typed out insid

相关标签:
12条回答
  • 2021-02-05 03:54

    Same as Ian's but shorter

    let countries = NSLocale.ISOCountryCodes().map { (code:String) -> String in
      let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
      return NSLocale(localeIdentifier: "en_US").displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
    }
    
    print(countries)
    
    0 讨论(0)
  • 2021-02-05 03:57

    Swift You can easily retrieve countries name and their flags emoji.

    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            var countriesData = [(name: String, flag: String)]()
    
            for code in NSLocale.isoCountryCodes  {
    
                let flag = String.emojiFlag(for: code)
                let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
    
                if let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) {
                    countriesData.append((name: name, flag: flag!))
                }else{
                     //"Country not found for code: \(code)"
                }
            }
    
            print(countriesData)
        }
    }
    
    
    extension String {
    
        static func emojiFlag(for countryCode: String) -> String! {
            func isLowercaseASCIIScalar(_ scalar: Unicode.Scalar) -> Bool {
                return scalar.value >= 0x61 && scalar.value <= 0x7A
            }
    
            func regionalIndicatorSymbol(for scalar: Unicode.Scalar) -> Unicode.Scalar {
                precondition(isLowercaseASCIIScalar(scalar))
    
                // 0x1F1E6 marks the start of the Regional Indicator Symbol range and corresponds to 'A'
                // 0x61 marks the start of the lowercase ASCII alphabet: 'a'
                return Unicode.Scalar(scalar.value + (0x1F1E6 - 0x61))!
            }
    
            let lowercasedCode = countryCode.lowercased()
            guard lowercasedCode.count == 2 else { return nil }
            guard lowercasedCode.unicodeScalars.reduce(true, { accum, scalar in accum && isLowercaseASCIIScalar(scalar) }) else { return nil }
    
            let indicatorSymbols = lowercasedCode.unicodeScalars.map({ regionalIndicatorSymbol(for: $0) })
            return String(indicatorSymbols.map({ Character($0) }))
        }
    }
    

    Result:

    0 讨论(0)
  • 2021-02-05 03:58

    SWIFT 4

    Here is an elegant way of doing it in Swift 4

    var countries: [String] = {
    
        var arrayOfCountries: [String] = []
    
        for code in NSLocale.isoCountryCodes as [String] {
            let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
            let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
            arrayOfCountries.append(name)
        }
    
        return arrayOfCountries
    }()
    
    0 讨论(0)
  • 2021-02-05 03:59

    also it is a good practise to localize the displayed name of countries. So in addition to vedo27 answer it would be:

    let countriesArray = NSLocale.ISOCountryCodes().map { (code:String) -> String in
            let id = NSLocale.localeIdentifierFromComponents([NSLocaleCountryCode: code])
            let currentLocaleID = NSLocale.currentLocale().localeIdentifier
            return NSLocale(localeIdentifier: currentLocaleID).displayNameForKey(NSLocaleIdentifier, value: id) ?? "Country not found for code: \(code)"
        }
    
    0 讨论(0)
  • 2021-02-05 04:03

    Update to vedo27's answer but in Swift 5:

    let countries : [String] = NSLocale.isoCountryCodes.map { (code:String) -> String in
            let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
            return NSLocale(localeIdentifier: "en_US").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
        }
    

    Also for having a sorted array for countries in Alphabetical order add this below in your order after fetching countries list

    let sortedcountries = countries.sorted { $0 < $1 }
    
    0 讨论(0)
  • 2021-02-05 04:04

    You can get a list of countries using the NSLocale class's isoCountryCodes which returns an array of [String]. From there, you get the country name by using NSLocale's displayName(forKey:) method. It looks like this:

    var countries: [String] = []
    
    for code in NSLocale.isoCountryCodes  {
        let id = NSLocale.localeIdentifier(fromComponents: [NSLocale.Key.countryCode.rawValue: code])
        let name = NSLocale(localeIdentifier: "en_UK").displayName(forKey: NSLocale.Key.identifier, value: id) ?? "Country not found for code: \(code)"
        countries.append(name)
    }
    
    print(countries)
    
    0 讨论(0)
提交回复
热议问题