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