目前我使用了以下代码,但它只返回两位数的代码
if let countryCode = (Locale.current as NSLocale).object(forKey: .countryCode) as? String {
print("Code => \(countryCode)") //FR
}
但我需要三位数代码(FRA),有人建议我获得ISO
639-2代码
此外,我已经检查了Apple文档,但我不知道如何获取确切的代码
谢谢。
在https://github.com/almerlucke/NSLocale-ISO639_2提供了Objective C解决方案。
这不会很难使用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]
}
}
不,你不能直接获得ISO代码,Locale不直接提供代码,你有另一种提取代码
https://github.com/lukes/ISO-3166-Countries-with-Regional-Codes/blob/master/all/all.json
从上面的URL下载json,它将为您提供所有国家/地区的详细信息,还包含带有alpha-2代码的ISO代码。
因此,您可以根据您的区域设置代码获取ISO(alpha-3)代码。