Updated 26 October 2021
Sometimes we need to make application for various language due to that reason we need to write string file in key value pair.
for this, we need to follow some steps.
1: create new string file name: Localizable.strings file.
2: select project from a project and set localization language like English, Arabic. (Actually, when you set language in swift it will create directory for each language like English: en.lproj file for each)
3: Now you create the global class that will access from any class.
4: write this function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
func language() { let languageCode = UserDefaults.standard if languageCode.object(forKey: "language") != nil { let language = languageCode.object(forKey: "language") var path :String = Bundle.main.path(forResource: language as! String?, ofType: "lproj")! if path .isEmpty { path = Bundle.main.path(forResource: "en", ofType: "lproj")! } languageBundle = Bundle(path: path) } else { languageCode.set("en", forKey: "language") languageCode.synchronize() let language = languageCode.string(forKey: "language")! var path = Bundle.main.path(forResource: language, ofType: "lproj")! if path .isEmpty { path = Bundle.main.path(forResource: "en", ofType: "lproj")! } languageBundle = Bundle(path: path) } } |
5: Now, time to access the file, here I have set for one language you can create for multiple languages by setting their code in (languageCode).
6: Write this function from any class
Here is code snippet:
1 2 |
globalObjectHome.language(); self.title = self.globalObjectHome.languageBundle.localizedString(forKey: "home", value: "", table: nil); |
If you have more details or questions, you can reply to the received confirmation email.
Back to Home
Be the first to comment.