forked from ArtSabintsev/Zephyr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Zephyr.swift
584 lines (382 loc) · 16.3 KB
/
Zephyr.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//
// Zephyr.swift
// Zephyr
//
// Created by Arthur Ariel Sabintsev on 11/2/15.
// Copyright © 2015 Arthur Ariel Sabintsev. All rights reserved.
//
import Foundation
/**
Enumerates the Local (NSUserDefaults) and Remote (NSUNSUbiquitousKeyValueStore) data stores
*/
private enum ZephyrDataStore {
case Local // NSUserDefaults
case Remote // NSUbiquitousKeyValueStore
}
public class Zephyr: NSObject {
/**
A debug flag.
If **true**, then this will enable console log statements.
By default, this flag is set to **false**.
*/
public static var debugEnabled = false
/**
The singleton for Zephyr.
*/
private static let sharedInstance = Zephyr()
/**
A shared key that stores the last synchronization date between NSUserDefaults and NSUbiquitousKeyValueStore
*/
private let ZephyrSyncKey = "ZephyrSyncKey"
/**
An array of keys that should be actively monitored for changes
*/
private var monitoredKeys = [String]()
/**
An array of keys that are currently registered for observation
*/
private var registeredObservationKeys = [String]()
/**
A session-persisted variable to directly access all of the NSUserDefaults elements
*/
private var ZephyrLocalStoreDictionary: [String: AnyObject] {
get {
return NSUserDefaults.standardUserDefaults().dictionaryRepresentation()
}
}
/**
A session-persisted variable to directly access all of the NSUbiquitousKeyValueStore elements
*/
private var ZephyrRemoteStoreDictionary: [String: AnyObject] {
get {
return NSUbiquitousKeyValueStore.defaultStore().dictionaryRepresentation
}
}
/**
Zephyr's initialization method
Do not call it directly.
*/
override init() {
super.init()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keysDidChangeOnCloud:", name: NSUbiquitousKeyValueStoreDidChangeExternallyNotification, object: nil)
}
/**
Zephyr's de-initialization method
*/
deinit {
NSNotificationCenter.defaultCenter().removeObserver(NSUbiquitousKeyValueStoreDidChangeExternallyNotification)
}
/**
Zephyr's synchronization method.
Zephyr will synchronize all NSUserDefaults with NSUbiquitousKeyValueStore.
If one or more keys are passed, only those keys will be synchronized.
- parameter keys: If you pass a one or more keys, only those key will be synchronized. If no keys are passed, than all NSUserDefaults will be synchronized with NSUbiquitousKeyValueStore.
*/
public static func sync(keys: String...) {
switch sharedInstance.dataStoreWithLatestData() {
case .Local:
if keys.count > 0 {
sync(keys)
} else {
printGeneralSyncStatus(false, destination: .Remote)
sharedInstance.syncToCloud()
printGeneralSyncStatus(true, destination: .Remote)
}
case .Remote:
if keys.count > 0 {
sync(keys)
} else {
printGeneralSyncStatus(false, destination: .Local)
sharedInstance.syncFromCloud()
printGeneralSyncStatus(true, destination: .Local)
}
}
}
/**
Overloaded version of Zephyr's synchronization method, **sync(_:)**.
This method will synchronize an array of keys between NSUserDefaults and NSUbiquitousKeyValueStore.
- parameter keys: An array of keys that should be synchronized between NSUserDefaults and NSUbiquitousKeyValueStore.
*/
public static func sync(keys: [String]) {
switch sharedInstance.dataStoreWithLatestData() {
case .Local:
printGeneralSyncStatus(false, destination: .Remote)
sharedInstance.syncSpecificKeys(keys, dataStore: .Local)
printGeneralSyncStatus(true, destination: .Remote)
case .Remote:
printGeneralSyncStatus(false, destination: .Local)
sharedInstance.syncSpecificKeys(keys, dataStore: .Remote)
printGeneralSyncStatus(true, destination: .Local)
}
}
/**
Add specific keys to be monitored in the background. Monitored keys will automatically
be synchronized between both data stores whenever a change is detected
- parameter keys: Pass one or more keys that you would like to begin monitoring.
*/
public static func addKeysToBeMonitored(keys: [String]) {
for key in keys {
if sharedInstance.monitoredKeys.contains(key) == false {
sharedInstance.monitoredKeys.append(key)
sharedInstance.registerObserver(key)
}
}
}
/**
Overloaded version of the **addKeysToBeMonitored(_:)** method.
Add specific keys to be monitored in the background. Monitored keys will automatically
be synchronized between both data stores whenever a change is detected
- parameter keys: Pass one or more keys that you would like to begin monitoring.
*/
public static func addKeysToBeMonitored(keys: String...) {
addKeysToBeMonitored(keys)
}
/**
Remove specific keys from being monitored in the background.
- parameter keys: Pass one or more keys that you would like to stop monitoring.
*/
public static func removeKeysFromBeingMonitored(keys: [String]) {
for key in keys {
if sharedInstance.monitoredKeys.contains(key) == true {
sharedInstance.monitoredKeys = sharedInstance.monitoredKeys.filter({$0 != key })
sharedInstance.unregisterObserver(key)
}
}
}
/**
Overloaded version of the **removeKeysFromBeingMonitored(_:)** method.
Remove specific keys from being monitored in the background.
- parameter keys: Pass one or more keys that you would like to stop monitoring.
*/
public static func removeKeysFromBeingMonitored(keys: String...) {
removeKeysFromBeingMonitored(keys)
}
}
// MARK: Helpers
private extension Zephyr {
/**
Compares the last sync date between NSUbiquitousKeyValueStore and NSUserDefaults.
If no data exists in NSUbiquitousKeyValueStore, then NSUbiquitousKeyValueStore will synchronize NSUserDefaults.
If no data exists in NSUserDefaults, then NSUserDefaults will synchronize NSUbiquitousKeyValueStore.
*/
func dataStoreWithLatestData() -> ZephyrDataStore {
if let remoteDate = ZephyrRemoteStoreDictionary[ZephyrSyncKey] as? NSDate,
localDate = ZephyrLocalStoreDictionary[ZephyrSyncKey] as? NSDate {
// If both localDate and remoteDate exist, compare the two, and the synchronize the data stores.
return localDate.timeIntervalSince1970 > remoteDate.timeIntervalSince1970 ? .Local : .Remote
} else {
// If remoteDate doesn't exist, then assume local data is newer.
guard let _ = ZephyrRemoteStoreDictionary[ZephyrSyncKey] as? NSDate else {
return .Local
}
// If localDate doesn't exist, then assume that remote data is newer.
guard let _ = ZephyrLocalStoreDictionary[ZephyrSyncKey] as? NSDate else {
return .Remote
}
// If neither exist, synchronize local data store to iCloud.
return .Local
}
}
}
// MARK: Synchronizers
private extension Zephyr {
/**
Synchronizes specific keys to/from NSUbiquitousKeyValueStore and NSUserDefaults.
- parameter keys: Array of leys to synchronize.
- parameter dataStore: Signifies if keys should be synchronized to/from iCloud.
*/
func syncSpecificKeys(keys: [String], dataStore: ZephyrDataStore) {
for key in keys {
switch dataStore {
case .Local:
let value = ZephyrLocalStoreDictionary[key]
syncToCloud(key: key, value: value)
case .Remote:
let value = ZephyrRemoteStoreDictionary[key]
syncFromCloud(key: key, value: value)
}
}
}
/**
Synchronizes all NSUserDefaults to NSUbiquitousKeyValueStore.
If a key is passed, only that key will be synchronized.
- parameter key: If you pass a key, only that key will updated in NSUbiquitousKeyValueStore.
- parameter value: The value that will be synchronized. Must be passed with a key, otherwise, nothing will happen.
*/
func syncToCloud(key key: String? = nil, value: AnyObject? = nil) {
let ubiquitousStore = NSUbiquitousKeyValueStore.defaultStore()
ubiquitousStore.setObject(NSDate(), forKey: ZephyrSyncKey)
// Sync all defaults to iCloud if key is nil, otherwise sync only the specific key/value pair.
guard let key = key else {
for (key, value) in ZephyrLocalStoreDictionary {
unregisterObserver(key)
ubiquitousStore.setObject(value, forKey: key)
Zephyr.printKeySyncStatus(key, value: value, destination: .Remote)
ubiquitousStore.synchronize()
registerObserver(key)
}
return
}
unregisterObserver(key)
if let value = value {
ubiquitousStore.setObject(value, forKey: key)
Zephyr.printKeySyncStatus(key, value: value, destination: .Remote)
} else {
ubiquitousStore.setObject(nil, forKey: key)
Zephyr.printKeySyncStatus(key, value: value, destination: .Remote)
}
ubiquitousStore.synchronize()
registerObserver(key)
}
/**
Synchronizes all NSUbiquitousKeyValueStore to NSUserDefaults.
If a key is passed, only that key will be synchronized.
- parameter key: If you pass a key, only that key will updated in NSUserDefaults.
- parameter value: The value that will be synchronized. Must be passed with a key, otherwise, nothing will happen.
*/
func syncFromCloud(key key: String? = nil, value: AnyObject? = nil) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(NSDate(), forKey: ZephyrSyncKey)
// Sync all defaults from iCloud if key is nil, otherwise sync only the specific key/value pair.
guard let key = key else {
for (key, value) in ZephyrRemoteStoreDictionary {
unregisterObserver(key)
defaults.setObject(value, forKey: key)
Zephyr.printKeySyncStatus(key, value: value, destination: .Local)
registerObserver(key)
}
return
}
unregisterObserver(key)
if let value = value {
defaults.setObject(value, forKey: key)
Zephyr.printKeySyncStatus(key, value: value, destination: .Local)
} else {
defaults.setObject(nil, forKey: key)
Zephyr.printKeySyncStatus(key, value: nil, destination: .Local)
}
registerObserver(key)
}
}
// MARK: Observers
extension Zephyr {
/**
Adds key-value observation after synchronization of a specific key.
- parameter key: The key that should be added and monitored.
*/
private func registerObserver(key: String) {
if key == ZephyrSyncKey {
return
}
if !registeredObservationKeys.contains(key) {
NSUserDefaults.standardUserDefaults().addObserver(self, forKeyPath: key, options: .New, context: nil)
registeredObservationKeys.append(key)
}
Zephyr.printObservationStatus(key, subscribed: true)
}
/**
Removes key-value observation before synchronization of a specific key.
- parameter key: The key that should be removed from being monitored.
*/
private func unregisterObserver(key: String) {
if key == ZephyrSyncKey {
return
}
if registeredObservationKeys.contains(key) {
NSUserDefaults.standardUserDefaults().removeObserver(self, forKeyPath: key, context: nil)
registeredObservationKeys = registeredObservationKeys.filter({$0 != key })
}
Zephyr.printObservationStatus(key, subscribed: false)
}
/**
Observation method for NSUbiquitousKeyValueStoreDidChangeExternallyNotification
*/
func keysDidChangeOnCloud(notification: NSNotification) {
if notification.name == NSUbiquitousKeyValueStoreDidChangeExternallyNotification {
guard let userInfo = notification.userInfo,
cloudKeys = userInfo[NSUbiquitousKeyValueStoreChangedKeysKey] as? [String],
localStoredDate = ZephyrLocalStoreDictionary[ZephyrSyncKey] as? NSDate,
remoteStoredDate = ZephyrRemoteStoreDictionary[ZephyrSyncKey] as? NSDate where remoteStoredDate.timeIntervalSince1970 > localStoredDate.timeIntervalSince1970 else {
return
}
for key in monitoredKeys where cloudKeys.contains(key) {
Zephyr.sync(key)
}
}
}
override public func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
guard let keyPath = keyPath, object = object else {
return
}
// Synchronize changes if key is monitored and if key is currently registered to respond to changes
if monitoredKeys.contains(keyPath) && registeredObservationKeys.contains(keyPath) {
if object is NSUserDefaults {
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: ZephyrSyncKey)
} else if object is NSUbiquitousKeyValueStore {
NSUbiquitousKeyValueStore.defaultStore().setObject(NSDate(), forKey: ZephyrSyncKey)
}
Zephyr.sync(keyPath)
}
}
}
// MARK: Loggers
private extension Zephyr {
/**
Prints Zephyr's current sync status if
debugEnabled == true
- parameter finished: The current status of syncing
*/
static func printGeneralSyncStatus(finished: Bool, destination dataStore: ZephyrDataStore) {
if debugEnabled == true {
let destination = dataStore == .Local ? "FROM iCloud" : "TO iCloud."
var message = "Started synchronization \(destination)"
if finished == true {
message = "Finished synchronization \(destination)"
}
printStatus(message)
}
}
/**
Prints the key, value, and destination of the synchronized information if
debugEnabled == true
- parameter key: The key being synchronized.
- parameter value: The value being synchronized.
- parameter destination: The data store that is receiving the updated key-value pair.
*/
static func printKeySyncStatus(key: String, value: AnyObject?, destination dataStore: ZephyrDataStore) {
if debugEnabled == true {
let destination = dataStore == .Local ? "FROM iCloud" : "TO iCloud."
guard let value = value else {
let message = "Synchronized key '\(key)' with value 'nil' \(destination)"
printStatus(message)
return
}
let message = "Synchronized key '\(key)' with value '\(value)' \(destination)"
printStatus(message)
}
}
/**
Prints the subscription state for a specific key if
debugEnabled == true
- parameter key: The key being synchronized.
- parameter subscribed: The subscription status of the key.
*/
static func printObservationStatus(key: String, subscribed: Bool) {
if debugEnabled == true {
let subscriptionState = subscribed == true ? "Subscribed" : "Unsubscribed"
let preposition = subscribed == true ? "for" : "from"
let message = "\(subscriptionState) '\(key)' \(preposition) observation."
printStatus(message)
}
}
/**
Prints a status to the console if
debugEnabled == true
- parameter status: The string that should be printed to the console.
*/
static func printStatus(status: String) {
if debugEnabled == true {
print("[Zephyr] \(status)")
}
}
}