2 // FolioReaderUserDefaults.swift
5 // Created by Kevin Delord on 01/04/17.
11 class FolioReaderUserDefaults {
13 /// User Defaults which are dependend on an identifier. If no identifier is given the default standard user defaults are used.
14 fileprivate var userDefaults = [String: Any]()
16 fileprivate var identifier: String?
18 fileprivate var useStandardUserDefaultsDirectly: Bool {
19 return (self.identifier == nil)
22 init(withIdentifier identifier: String?) {
23 if let _identifier = identifier {
24 self.identifier = "folioreader.userdefaults.identifier.\(_identifier)"
28 let prefixedIdentifier = self.identifier,
29 let defaults = UserDefaults.standard.value(forKey: prefixedIdentifier) as? [String: Any] else {
33 self.userDefaults = defaults
36 public func synchronize() {
37 if let identifier = self.identifier {
38 // Add the keys to to the user defaults it they are identifier dependend
39 UserDefaults.standard.set(self.userDefaults, forKey: identifier)
42 UserDefaults.standard.synchronize()
48 extension FolioReaderUserDefaults {
50 internal func bool(forKey key: String) -> Bool {
51 guard (self.useStandardUserDefaultsDirectly == false) else {
52 return ((UserDefaults.standard.object(forKey: key) as? Bool) ?? false)
55 guard let value = self.userDefaults[key] as? Bool else {
62 internal func integer(forKey key: String) -> Int {
63 guard (self.useStandardUserDefaultsDirectly == false) else {
64 return ((UserDefaults.standard.object(forKey: key) as? Int) ?? 0)
67 guard let value = self.userDefaults[key] as? Int else {
74 internal func value(forKey key: String) -> Any? {
75 guard (self.useStandardUserDefaultsDirectly == false) else {
76 return UserDefaults.standard.object(forKey: key)
79 return self.userDefaults[key]
84 extension FolioReaderUserDefaults {
86 internal func register(defaults: [String: Any]) {
87 guard (self.useStandardUserDefaultsDirectly == false) else {
88 UserDefaults.standard.register(defaults: defaults)
92 for (key, value) in defaults where (self.userDefaults[key] == nil) {
93 self.userDefaults[key] = value
99 internal func set(_ value: Any?, forKey key: String) {
100 if (self.useStandardUserDefaultsDirectly == true) {
101 UserDefaults.standard.set(value, forKey: key)
103 self.userDefaults[key] = value