Govind Rakholiya
Govind Rakholiya

Reputation: 295

localization in ios swift. how can i change application language at run time

i am creating app in ios swift. now i want to make app in dual language so from editor menu i just export and import for localization. its create two file for me.enter image description here

now i want to put two button on first page of my app. and when user press button 1 i want to load english language. and if user press button 2 i want to load turkish language. so how can i do this in swift?

Upvotes: 2

Views: 10991

Answers (2)

wakachamo
wakachamo

Reputation: 1763

Please don't do this. This leads to a very confusing user experience; people expect their apps to run in the system language they choose.

You'll also run into problems when it comes to UI and strings that you do not control, like system view controllers (e.g. sharing files) and formatters for dates, numbers, quantities, etc.

If every application had a language switcher by default, it would be a very cumbersome experience to go and select it for every app. This is why the localisation API is structured the way it is; if you use the system language fallback, then everything will work the way it should.

Upvotes: 1

Michaël Azevedo
Michaël Azevedo

Reputation: 3894

Instead of using NSLocalizedString method to localize your App, load the localizable strings according to the language selected and use it from your code.

Loading the data from the bundle :

// Exemple with english language
if let path = NSBundle(forClass:object_getClass(self)).URLForResource("Localizable", withExtension: "strings", subdirectory: nil, localization: "en")?.path {
    if NSFileManager.defaultManager().fileExistsAtPath(path)     {
        // Keep a reference to this dictionary
        dicoLocalisation = NSDictionary(contentsOfFile: path)
    }
}

Replacing NSLocalizedString :

func localizedStringForKey(key:String) -> String { 
    // First we check if the dictionary exists       
    if let dico = dicoLocalisation {

        if let localizedString = dico[key] as? String {
            // If the localization exists, return it
            return localizedString
        }  else {
            // Returns the key if no String was found
            return key
        }
    } else {
        // If not, we can use the NSLocalizedString function
        return NSLocalizedString(key, comment: key)
    }
}

If you want to handle this quickly, I've made a custom localisator class available on Github, which allow you to switch language from anywhere in the app and even save if for further launches of the app. The implementation is pretty much the same as what I've explained.

Upvotes: 4

Related Questions