25
25
26
26
import Foundation
27
27
28
+ internal protocol ICloudStore {
29
+ var dictionaryRepresentation : [ String : Any ] { get }
30
+
31
+ func object( forKey defaultName: String ) -> Any ?
32
+ func set( _ anObject: Any ? , forKey aKey: String )
33
+ @discardableResult func synchronize( ) -> Bool
34
+ }
35
+
36
+ extension NSUbiquitousKeyValueStore : ICloudStore {
37
+ }
38
+
39
+
28
40
internal class DefaultsSyncer {
29
41
30
- let defaults : UserDefaults
42
+ private let defaults : UserDefaults
43
+ private let iCloudStore : ICloudStore
31
44
32
45
var syncedKeys = Set < String > ( )
33
46
34
- init ( defaults: UserDefaults ) {
47
+ init ( defaults: UserDefaults , iCloudStore : ICloudStore ) {
35
48
self . defaults = defaults
49
+ self . iCloudStore = iCloudStore
50
+
36
51
NotificationCenter . default. addSafeObserver ( self ,
37
52
selector: #selector( iCloudDefaultsDidUpdate) ,
38
53
name: NSUbiquitousKeyValueStore . didChangeExternallyNotification)
@@ -61,10 +76,10 @@ internal class DefaultsSyncer {
61
76
}
62
77
63
78
// Implementation
64
- let allICloudKeys = Set ( NSUbiquitousKeyValueStore . default . dictionaryRepresentation. keys)
79
+ let allICloudKeys = Set ( iCloudStore . dictionaryRepresentation. keys)
65
80
let updatedSyncedKeys = allICloudKeys. filter { syncedKeys. contains ( $0) }
66
81
updatedSyncedKeys. forEach { key in
67
- let iCloudValue = NSUbiquitousKeyValueStore . default . object ( forKey: key)
82
+ let iCloudValue = iCloudStore . object ( forKey: key)
68
83
defaults. set ( iCloudValue, forKey: key)
69
84
}
70
85
}
@@ -74,10 +89,10 @@ internal class DefaultsSyncer {
74
89
guard !syncedKeys. isEmpty else { return }
75
90
syncedKeys. forEach { key in
76
91
let localValue = defaults. object ( forKey: key)
77
- NSUbiquitousKeyValueStore . default . set ( localValue, forKey: key)
92
+ iCloudStore . set ( localValue, forKey: key)
78
93
}
79
94
// request upload to ICloud
80
- NSUbiquitousKeyValueStore . default . synchronize ( )
95
+ iCloudStore . synchronize ( )
81
96
}
82
97
83
98
deinit {
0 commit comments