Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Localize Internal Frameworks like UIKit without App restart

I have to add an option of switching language inside the app only. I am just stuck on with localizing internal framworks. Can anyone help me with localization of internal framework like UIKit etc from the app itself without restart. My code works fine but for the case of internal framework requires a restart. Just the internal frameworks are not getting localized.

My current code is :

Create a file named BundleExtension.swift and add the following code to it -

var bundleKey: UInt8 = 0

class AnyLanguageBundle: Bundle {

override func localizedString(forKey key: String,
                              value: String?,
                              table tableName: String?) -> String {

    guard let path = objc_getAssociatedObject(self, &bundleKey) as? String,
        let bundle = Bundle(path: path) else {

            return super.localizedString(forKey: key, value: value, table: tableName)
    }

    return bundle.localizedString(forKey: key, value: value, table: tableName)
  }
}

extension Bundle {

class func setLanguage(_ language: String) {

    defer {

        object_setClass(Bundle.main, AnyLanguageBundle.self)
    }

    objc_setAssociatedObject(Bundle.main, &bundleKey,    Bundle.main.path(forResource: language, ofType: "lproj"), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
  }
}

Now whenever you need to change the language call this method :

func languageButtonAction() {
    // This is done so that network calls now have the Accept-Language as "hi" (Using Alamofire) Check if you can remove these
    UserDefaults.standard.set(["hi"], forKey: "AppleLanguages")
    UserDefaults.standard.synchronize()

    // Update the language by swaping bundle
    Bundle.setLanguage("hi")

    // Done to reintantiate the storyboards instantly
    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    UIApplication.shared.keyWindow?.rootViewController = storyboard.instantiateInitialViewController()
}
like image 948
Ankit Kumar Gupta Avatar asked Jan 29 '18 10:01

Ankit Kumar Gupta


1 Answers

Check this demo, it will work for you.

Link

like image 182
Bhupesh Avatar answered Oct 04 '22 06:10

Bhupesh