@@ -11,12 +11,15 @@ import Combine
11
11
protocol UserDefaultsService {
12
12
func saveRecentSnippet( _ snippet: Snippet )
13
13
func fetchRecentSnippets( ) -> AnyPublisher < [ Snippet ] , Never >
14
+
15
+ func fetchRecentSnippetsFromAppGroup( ) -> [ Snippet ]
14
16
}
15
17
16
18
final class UserDefaultsServiceImpl : UserDefaultsService {
17
19
18
20
private enum Constants {
19
21
static let recentSnippetKey = " RecentSnippet "
22
+ static let appGroupName = " group.com.cphlowiec.SnippetsLibrary "
20
23
}
21
24
22
25
// MARK: - Stored Properties
@@ -25,13 +28,21 @@ final class UserDefaultsServiceImpl: UserDefaultsService {
25
28
26
29
// MARK: - Methods
27
30
31
+ // MARK: - Recent Snippets -
32
+
28
33
internal func saveRecentSnippet( _ snippet: Snippet ) {
29
34
let snippet = SnippetPlist ( from: snippet)
30
35
let snippetDictonary = snippet. convertedToDictonary ( )
36
+ let snippetKey = Constants . recentSnippetKey + " \( snippet. id) "
31
37
32
38
userDefaults. set (
33
39
snippetDictonary,
34
- forKey: Constants . recentSnippetKey + " \( snippet. id) "
40
+ forKey: snippetKey
41
+ )
42
+
43
+ saveSnippetDictonaryIntoAppGroup (
44
+ snippetDictonary,
45
+ key: snippetKey
35
46
)
36
47
}
37
48
@@ -56,4 +67,37 @@ final class UserDefaultsServiceImpl: UserDefaultsService {
56
67
. eraseToAnyPublisher ( )
57
68
}
58
69
70
+ // MARK: - App Group -
71
+
72
+ internal func fetchRecentSnippetsFromAppGroup( ) -> [ Snippet ] {
73
+ guard let userDefaults = UserDefaults ( suiteName: Constants . appGroupName) else { return [ ] }
74
+
75
+ let keys = userDefaults. dictionaryRepresentation ( ) . keys. filter { $0. contains ( Constants . recentSnippetKey) }
76
+ var snippets = [ Snippet] ( )
77
+
78
+ for key in keys {
79
+ guard
80
+ let snippetDictonary = userDefaults. object ( forKey: key) ,
81
+ let data = try ? JSONSerialization . data ( withJSONObject: snippetDictonary, options: [ ] ) ,
82
+ let snippet = try ? JSONDecoder ( ) . decode ( SnippetPlist . self, from: data)
83
+ else { continue }
84
+
85
+ snippets. append ( Snippet ( from: snippet) )
86
+ }
87
+
88
+ return snippets
89
+ }
90
+
91
+ private func saveSnippetDictonaryIntoAppGroup(
92
+ _ snippetDictonary: [ String : Any ] ,
93
+ key: String
94
+ ) {
95
+ guard let userDefaults = UserDefaults ( suiteName: Constants . appGroupName) else { return }
96
+
97
+ userDefaults. set (
98
+ snippetDictonary,
99
+ forKey: key
100
+ )
101
+ }
102
+
59
103
}
0 commit comments