Thursday 16 March 2017

how to get current device language in english as display name in iOS

Hello,  I am here once again with a new blog. In this we will see how to get the device language in an iOS app. When we see first time, it seems very easy to get the current device language. The NSLocale class provides all methods to get most of the device information out of it.

So let's do write some line of code to get the device language:

1) To get the current identifier :
   
     NSLocale.current.identifier

If your device using en-US as language , the above line will return en_US as a result. 

2) But the this is not what I was looking for. I have to show the full  language name in my last project. For example English for en, German for de and so on as listed  in apple spec. 
To show the full language name as I wanted, I  googled many pages and found answer on stackoverflow as:

a) Get the first element from the array of preferred languages:  

        let lang = NSLocale.preferredLanguages[0]

b) Get the locale object

    let locale = NSLocale(localeIdentifier: lang)

c) Get the localized string for a language code

 let fullName = locale.localizedString(forLanguageCode: lang)!

In first line we get the language identifier from the array of preferred language . This array holds the language identifier for each language shown in preferred language category in an iOS device. Each element of this array show the abbreviate form for the given language(en_US for English (United state) and so on). 

In second line we got  the NSLocale object by passing language identifier got in step 1. And in last line we get the localized string for the language code from locale object created in step 2.

On execution of above lines of code, the result will be English for en_US, Deutsch for de-DE.

But what is this? It's not what I was looking for yet . The above code give the localized name for the given  identifier. From  output we can see that if my device is using some symbolic language like Chinese, the output will also be symbolic.

Now to show the name of the language in English , for example English for identifier  en, German for identifier de, Chinese for identifier zh, change the identifier parameter of  NSLocale(identifier:) to "en" as:

    let locale = NSLocale(localeIdentifier: "en")

That's it.

1 comment:

  1. If you are interested in trying new localization tools for your projects, my suggestion is to have a look at https://poeditor.com. The interface is simple and has lots of automation features to make things easier. It's worth a shot.

    ReplyDelete