-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathInitEventsStorage.swift
42 lines (34 loc) · 1.29 KB
/
InitEventsStorage.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
import Foundation
protocol InitEventsStorage {
func saveInitEvent(_ event: InitEvent)
func fetchInitEvents() -> [InitEvent]
func clearInitEvents()
}
class UserDefaultsInitEventsStorage: InitEventsStorage {
private let initEventsKey = "com.walletconnect.sdk.initEvents"
private let maxEvents = 100
func saveInitEvent(_ event: InitEvent) {
// Fetch existing events from UserDefaults
var existingEvents = fetchInitEvents()
existingEvents.append(event)
// Ensure we keep only the last 100 events
if existingEvents.count > maxEvents {
existingEvents = Array(existingEvents.suffix(maxEvents))
}
// Save updated events back to UserDefaults
if let encoded = try? JSONEncoder().encode(existingEvents) {
UserDefaults.standard.set(encoded, forKey: initEventsKey)
}
}
func fetchInitEvents() -> [InitEvent] {
if let data = UserDefaults.standard.data(forKey: initEventsKey),
let events = try? JSONDecoder().decode([InitEvent].self, from: data) {
// Return only the last 100 events
return Array(events.suffix(maxEvents))
}
return []
}
func clearInitEvents() {
UserDefaults.standard.removeObject(forKey: initEventsKey)
}
}