iOS Get localized version of a string for a specific language

梦想的初衷 提交于 2019-12-03 12:27:26
dvp.petrov

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!