-
Notifications
You must be signed in to change notification settings - Fork 0
/
SwiftyiCloudSync.swift
61 lines (51 loc) · 2.21 KB
/
SwiftyiCloudSync.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
//
// SwiftyiCloudSync.swift
// SwiftyiCloudSync
//
// Created by Kurt Jensen on 1/15/17.
// Copyright © 2017 Kurt Jensen. All rights reserved.
//
import Foundation
class SwiftyiCloudSync {
static var prefix: String?
class func shouldSyncKey(_ key: String) -> Bool {
guard let prefix = prefix else { return true }
return key.hasPrefix(prefix)
}
class func start(prefix: String?) {
SwiftyiCloudSync.prefix = prefix
addObservers()
}
@objc class func updateUserDefaultsFromiCloud(_ notification: NSNotification?) {
removeObservers()
let iCloudDictionary = NSUbiquitousKeyValueStore.default().dictionaryRepresentation
let userDefaults = UserDefaults.standard
for (key, value) in iCloudDictionary {
if shouldSyncKey(key) {
userDefaults.set(value, forKey: key)
debugPrint("updateUserDefaults", (key, value))
}
}
userDefaults.synchronize()
addObservers()
}
@objc class func updateiCloudFromUserDefaults(_ notification: NSNotification?) {
let defaultsDictionary = UserDefaults.standard.dictionaryRepresentation()
let cloudStore = NSUbiquitousKeyValueStore.default()
for (key, value) in defaultsDictionary {
if shouldSyncKey(key) {
cloudStore.set(value, forKey: key)
debugPrint("updateiCloud", (key, value))
}
}
cloudStore.synchronize()
}
class func addObservers() {
NotificationCenter.default.addObserver(self, selector: #selector(SwiftyiCloudSync.updateUserDefaultsFromiCloud(_:)), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(SwiftyiCloudSync.updateiCloudFromUserDefaults(_:)), name: UserDefaults.didChangeNotification, object: nil)
}
class func removeObservers() {
NotificationCenter.default.removeObserver(self, name: UserDefaults.didChangeNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: nil)
}
}