Skip to content

Instantly share code, notes, and snippets.

@afshin-hoseini
Created November 20, 2017 07:12
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save afshin-hoseini/a46f431fbe6bb20fde8e8ed675e81018 to your computer and use it in GitHub Desktop.
Save afshin-hoseini/a46f431fbe6bb20fde8e8ed675e81018 to your computer and use it in GitHub Desktop.
Forcing change localization for first iOS application run
//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
}
@afshin-hoseini
Copy link
Author

afshin-hoseini commented Nov 20, 2017

This is the swift version of this stack overflow answer

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment