Last active
September 24, 2017 03:49
-
-
Save danielbas/0fd75be984927801e0ffbd8bf45f5846 to your computer and use it in GitHub Desktop.
In app localization manager
This file contains 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
import Foundation | |
enum LanguageCode: String { | |
case en | |
case zh | |
case ja | |
} | |
class InAppLocalizationManager { | |
static var shared: InAppLocalizationManager { | |
return mInstance | |
} | |
private static let mInstance = InAppLocalizationManager() | |
private let localizationDictionary: [String: String] | |
private(set) var languageCode = LanguageCode.en | |
init() { | |
let fileUrl = Bundle.main.url(forResource: "LocalizedStrings", withExtension: "plist") | |
let data = try? Data(contentsOf: fileUrl!) | |
localizationDictionary = try! PropertyListSerialization.propertyList(from: data!, options: [], format: nil) as! [String: String] | |
reloadLanguageCode() | |
} | |
/// Get the string in the localization dictionary by the key. | |
/// | |
/// - Parameter key: The localization key | |
/// - Returns: The string if there is one string corresponding to the key in the dictionary, otherwise returns `nil`. | |
func localizedString(_ key: String) -> String? { | |
let localizeKey = key + "." + languageCode.rawValue | |
return localizationDictionary[localizeKey] | |
} | |
/// Reload the language code from the language preference in user defaults, or from the system locale if there's no language preference in user defaults. | |
func reloadLanguageCode() { | |
if let code = UserDefaults.standard.string(forKey: "inApplanguageCode") { | |
languageCode = LanguageCode.init(rawValue: code)! | |
} else if let code = Locale.current.languageCode { | |
languageCode = LanguageCode.init(rawValue: code) ?? .en // The user's device language setting may not be in the enum `LanguageCode` | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment