iOS Get localized version of a string for a specific language

后端 未结 1 942
后悔当初
后悔当初 2021-02-14 05:23

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 understandi

1条回答
  •  时光说笑
    2021-02-14 05:51

    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.

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