Nandhakumar
Nandhakumar

Reputation: 74

How to Get the ISO 639-2 country Code on iOS using Swift

Currently I used the following code , but it will return only two digit code

    if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
      print("Code => \(countryCode)") //FR
    }

but I need the three digit code (FRA) , Kindly anyone suggest me to get the ISO

639-2 code

Also I have checked the Apple doc , but I don't know how to get the exact code

enter image description here

https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPInternational/LanguageandLocaleIDs/LanguageandLocaleIDs.html#//apple_ref/doc/uid/10000171i-CH15

Thank you.

Upvotes: 5

Views: 6429

Answers (2)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

An Objective C solution is provided at https://github.com/almerlucke/NSLocale-ISO639_2.

This won't be to hard to create load your own using https://github.com/almerlucke/NSLocale-ISO639_2/blob/master/Resources/iso639_2.bundle/iso639_1_to_iso639_2.plist

public extension Locale {

    private static let allIso639_2LanguageIdentifiers: [String: String] = {
        guard let path = Bundle.main.path(forResource: "iso639_1_to_iso639_2", ofType: "plist") else { return [:] }
        guard let result = NSDictionary(contentsOfFile: path) as? [String: String] else { return [:] }

        return result
    }()

    public var iso639_2LanguageCode: String? {
        guard let languageCode = languageCode else { return nil }
        return Locale.allIso639_2LanguageIdentifiers[languageCode]
    }

}

Upvotes: 4

Jaydeep Vora
Jaydeep Vora

Reputation: 6213

No you can't get the ISO code directly, Locale doesn't provide code directly, you have extract code another way

https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes/blob/master/all/all.json

Download json from above URL, it will provide you a all Country with details, also contain ISO code with alpha-2 code.

So you can get the ISO(alpha-3) code as per your locale code.

Upvotes: 1

Related Questions