Created
September 21, 2018 13:57
-
-
Save gbrl0chn/8d6115caa744c266b210df659a049386 to your computer and use it in GitHub Desktop.
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
// | |
// Bundle+InAppLanguage.swift | |
// | |
// Created by Gabriel Chen on 2018/9/20. | |
// Copyright © 2018 Gabriel Chen All rights reserved. | |
// | |
import Foundation | |
fileprivate var kALB = 0 // Associated Language Bundle | |
// MARK: ---------- Private Custom Bundle ---------- | |
fileprivate class MyBundle: Bundle { | |
override func localizedString(forKey key: String, value: String?, table tableName: String?) -> String { | |
guard let bundle = objc_getAssociatedObject(self, &kALB) as? Bundle else { | |
return super.localizedString(forKey: key, value: value, table: tableName) | |
} | |
return bundle.localizedString(forKey: key, value: value, table: tableName) | |
} | |
} | |
// MARK: ---------- Bundle Extension ---------- | |
extension Notification.Name { | |
static let languageWasChanged = Notification.Name(rawValue: "ag_languageWasChanged") | |
} | |
extension Bundle { | |
private static let dispatch_once: () = { | |
object_setClass(Bundle.main, MyBundle.self) | |
}() | |
@discardableResult | |
class func setLanguage(_ code: String) -> Bool { | |
dispatch_once | |
guard let bundlePath = Bundle.main.path(forResource: code, ofType: "lproj") else { | |
return false | |
} | |
let bundle = Bundle(path: bundlePath) | |
let policy = objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC | |
objc_setAssociatedObject(Bundle.main, &kALB, bundle, policy) | |
UserDefaults.standard.set([code], forKey: "AppleLanguages") | |
NotificationCenter.default.post(name: .languageWasChanged, object: code) | |
return true | |
} | |
class var language: String? { | |
if let bundle = objc_getAssociatedObject(Bundle.main, &kALB) as? Bundle { | |
let path = bundle.bundlePath as NSString | |
if let fileName = path.pathComponents.last as NSString? { | |
return fileName.deletingPathExtension | |
} | |
} | |
return Bundle.main.preferredLocalizations.first | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment