swift 获取当前系统语言

OC语言:

+ (NSString*)getPreferredLanguage{

        NSUserDefaults* defs = [NSUserDefaults standardUserDefaults];

        NSArray* languages = [defs objectForKey:@"AppleLanguages"];

        NSString* preferredLang = [languages objectAtIndex:0];

        return preferredLang;

}

swift 语言:

func getCurrentLanguage() -> String{

       let defs = NSserDefaults.standardUserDefaults()

       let languages = defs.objectForKey("AppleLanguages")//获取系统支持的所有语言集合

       let preferredLanguage = languages!.objectAtIndex(0)//集合第一个元素为当前语言

       return String(prefrredLanguage)//若当前系统为英文,则返回en_US

}

swift升级版:

   static func getCurrentLanguage() -> String {
//        let defs = UserDefaults.standard
//        let languages = defs.object(forKey: "AppleLanguages")
//        let preferredLang = (languages! as AnyObject).object(0)
        let preferredLang = Bundle.main.preferredLocalizations.first! as NSString
//        let preferredLang = (languages! as AnyObject).object(0)
        Log.debug("当前系统语言:\(preferredLang)")
        
        switch String(describing: preferredLang) {
        case "en-US", "en-CN":
            return "en"//英文
        case "zh-Hans-US","zh-Hans-CN","zh-Hant-CN","zh-TW","zh-HK","zh-Hans":
            return "cn"//中文
        default:
            return "en"
        }
    }

你可能感兴趣的:(swift 获取当前系统语言)