How to get current language code with Swift?

前端 未结 13 2034
难免孤独
难免孤独 2020-12-07 11:06

I want get the language code of the device (en, es...) in my app written with Swift. How can get this?

I\'m trying this:

var preferredLanguages : NSL         


        
相关标签:
13条回答
  • 2020-12-07 11:36

    Swift 5.3:

    let languagePrefix = Locale.preferredLanguages[0]
    print(languagePrefix)
    
    0 讨论(0)
  • 2020-12-07 11:37

    In Swift 3

    let langStr = Locale.current.languageCode
    
    0 讨论(0)
  • 2020-12-07 11:38

    It's important to make the difference between the App language and the device locale language (The code below is in Swift 3)

    Will return the Device language:

    let locale = NSLocale.current.languageCode
    

    Will return the App language:

    let pre = Locale.preferredLanguages[0]
    
    0 讨论(0)
  • 2020-12-07 11:44

    you may use the below code it works fine with swift 3

    var preferredLanguage : String = Bundle.main.preferredLocalizations.first!
    
    0 讨论(0)
  • 2020-12-07 11:47

    In Swift 3:

    NSLocale.current.languageCode
    
    0 讨论(0)
  • 2020-12-07 11:48

    Swift 3 & 4 & 4.2 & 5

    Locale.current.languageCode does not compile regularly. Because you did not implemented localization for your project.

    You have two possible solutions

    1) String(Locale.preferredLanguages[0].prefix(2)) It returns phone lang properly.

    If you want to get the type en-En, you can use Locale.preferredLanguages[0]

    2) Select Project(MyApp)->Project (not Target)-> press + button into Localizations, then add language which you want.

    0 讨论(0)
提交回复
热议问题