Created
November 20, 2017 07:12
-
-
Save afshin-hoseini/a46f431fbe6bb20fde8e8ed675e81018 to your computer and use it in GitHub Desktop.
Forcing change localization for first iOS application run
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//First, define a custom bundle class as like as below | |
import Foundation | |
//A key used for exchanging associated object | |
var _BUNDLE_KEY = 0 | |
class BundleEx : Bundle { | |
override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String { | |
let bundle : Bundle? = objc_getAssociatedObject(self, &_BUNDLE_KEY) as? Bundle | |
return bundle != nil ? bundle!.localizedString(forKey: key, value: value, table: tableName) : super.localizedString(forKey: key, value: value, table: tableName) | |
} | |
} | |
//Second, in App delegate.application(_ : didFinishLaunchingWithOptions:) try to swizzle the Bundle.main. | |
//This snippet only runs for the first application execution. In further executions it won't be executed since the langs array will contain | |
// "fa" language | |
let langs = UserDefaults.standard.value(forKey: "AppleLanguages") as? [String] | |
if langs == nil || !langs!.contains("fa") { | |
UserDefaults.standard.set(["fa-IR", "fa", "en"], forKey: "AppleLanguages" ) | |
UserDefaults.standard.synchronize() | |
object_setClass(Bundle.main, BundleEx.self) | |
let bundle = Bundle(path: Bundle.main.path(forResource: "fa-IR", ofType: "lproj")!) | |
objc_setAssociatedObject(Bundle.main, &_BUNDLE_KEY, bundle, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) | |
//Changes the direction of all views. You omit it if the determined language is LTR | |
UIView.appearance().semanticContentAttribute = .forceRightToLeft | |
let sb = UIStoryboard(name: "Main", bundle: Bundle.main) | |
let vc = sb.instantiateInitialViewController() | |
self.window?.rootViewController = vc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is the swift version of this stack overflow answer