swiftuiios17country-codes

How to get and display country name as 2 letters rather than full country name


I am trying to implement the Country Codes in my app for Phone Auth Login. This is a SwiftUI app using iOS 17 and below is the code i am using to implement this but it is printing out the full Country Name rather than the 2 letters of the country as listed at Country Codes.

I was able to find some information at a previous post by another user: Getting country name from country code but this just displayed the Country in full name and not in the 2-letter format.

Below is the Code acquired:

Getting Country Code:

func getCountryCode() -> String {
        let regionCode = Locale.current.region?.identifier ?? ""
        return countries[regionCode] ?? ""
    }

Getting Country Name:

func countryName(countryCode: String) -> String? {
    let current = Locale(identifier: Locale.current.identifier)
    return current.localizedString(forRegionCode: countryCode)
}

Implementing code in my LoginView:

HStack {
    // displays CountryName: full NOT 2-letter identifier
    Text("\(loginData.countryName(countryCode: regionCode) ?? "")")
    
    // displays CountryCode
    Text("+ \(loginData.getCountryCode())")
}
                            

When i display the above in my app, this is how it is displayed:

United States  +1

How I need it displayed:

US +1

Solution

  • to get the country codes, you could try this approach, for example with country code in a HStack.

    Example code:

    struct ContentView: View {
        let countryCodes = Locale.Region.isoRegions.compactMap{$0.identifier}
        
        var body: some View {
            List(countryCodes, id: \.self) { code in
                HStack {
                    Text(code)
                    Text(" + ....")
                }
            }
        }
    }
    

    EDIT-1:

    a more principled code version:

    struct Country: Identifiable {
        let id = UUID()
        var name: String
        var code: String
        // others, eg telephone code
    }
    
    struct ContentView: View {
        @State private var countries: [Country] = []
        
        var body: some View {
            List(countries) { country in
                HStack {
                    Text(country.code)
                    Text(" + ....")
                }
            }
            .onAppear {
                Locale.Region.isoRegions.compactMap{$0.identifier}.forEach{ code in
                    if let name = Locale(identifier: code).localizedString(forRegionCode: code) {
                        countries.append(Country(name: name, code: code))
                    }
                }
            }
        }
    }