I want to change the language of the application. I have created two files for Main.strings in English and Hindi. Also Localizable.strings for both Hindi and English. Here is how I change the language :
LocalizationSystem.sharedInstance.setLanguage(languageCode: "hi")
UIView.appearance().semanticContentAttribute = .forceLeftToRight
let storyboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "SwipeViewController")as! SwipeViewController
let navigationController = UINavigationController(rootViewController: vc)
navigationController.modalPresentationStyle = .overFullScreen
UIApplication.shared.keyWindow?.rootViewController = navigationController
Here is the LocalizationSystem class
class LocalizationSystem : NSObject {
var bundle: Bundle!
class var sharedInstance: LocalizationSystem {
struct Singleton {
static let instance: LocalizationSystem = LocalizationSystem()
}
return Singleton.instance
}
override init() {
super.init()
bundle = Bundle.main
}
func localizedStringForKey(key:String, comment:String) -> String {
return bundle.localizedString(forKey: key, value: comment, table: nil)
}
func localizedImagePathForImg(imagename:String, type:String) -> String {
guard let imagePath = bundle.path(forResource: imagename, ofType: type) else {
return ""
}
return imagePath
}
func setLanguage(languageCode:String) {
var appleLanguages = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
appleLanguages.remove(at: 0)
appleLanguages.insert(languageCode, at: 0)
UserDefaults.standard.set(appleLanguages, forKey: "AppleLanguages")
UserDefaults.standard.synchronize() //needs restrat
if let languageDirectoryPath = Bundle.main.path(forResource: languageCode, ofType: "lproj") {
bundle = Bundle.init(path: languageDirectoryPath)
} else {
resetLocalization()
}
}
func resetLocalization() {
bundle = Bundle.main
}
func getLanguage() -> String {
let appleLanguages = UserDefaults.standard.object(forKey: "AppleLanguages") as! [String]
let preferredLanguage = appleLanguages[0]
if preferredLanguage.contains("-") {
let array = preferredLanguage.components(separatedBy: "-")
return array[0]
}
return preferredLanguage
}
}
Localizable.strings
file is changing but Main.Strings
file doesn't changes without restart of the application.
I don't know what I am missing here.
Thanks in advance