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

后端 未结 12 1620
日久生厌
日久生厌 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: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:

提交回复
热议问题