Search code examples
iosxcodelocalizationinternationalizationnslocalizedstring

iOS Get localized version of a string for a specific language


I'm building an application for iOS that will be available in both English and French languages. I've read some tutorials around internationalization and I have an understanding of how it works and what I need to do.

The problem I'm having is there is a specific case where I want to load French strings for an English user.

I understand it's possible to set the language for the entire application, but that it requires the application to be restarted before it will take affect. I'd like to avoid this, and instead be able to pick to load French or English strings on demand.

Is it possible to load strings from a .strings file for a specific language programmatically?


Solution

  • Yes, it is possible, but it is not that easy to accomplished.

    I just have the case, where I should send one and the same name(for all languages) of a ViewController for GAI (Google Analytics for iOS).

    Preconditions:

    1) I use the NSBundle extension from here https://stackoverflow.com/a/20257557/3883492 - maybe it is a good idea to look up there first. (It is pretty genius to be honest)

    2) I am using swift 2

    Here is a pretty simple code sample to illustrate my idea:

    func getFrenchString(forKey key: String) -> String {
        if let currentLanguage = (NSUserDefaults.standardUserDefaults().arrayForKey(AppleLanguages)?.first as? String) {
            if currentLanguage == "fr" {
                return NSLocalizedString(key, comment: "")
            }
            else {
                //the application is not currently on `fr`
                //change application to `fr`
                NSBundle.setLanguage("fr")
    
                //get the localized string on `fr`
                let frString = NSLocalizedString(key, comment: "")
    
                //return the application to the old language
                NSBundle.setLanguage(currentLanguage)
    
                return frString
            }
        }
    
        return ""
    }
    

    Also you should have "fr.lproj" folder with localised string in your project.