51 lines
1.4 KiB
Swift
51 lines
1.4 KiB
Swift
import Foundation
|
|
|
|
final class AppStateService {
|
|
static let shared = AppStateService()
|
|
|
|
private let configKey = "bugger.config"
|
|
private let seenBugsKey = "bugger.seenBugs"
|
|
|
|
private(set) var config: AppConfig? {
|
|
didSet { persistConfig() }
|
|
}
|
|
|
|
private(set) var persistedSeenBugs: Set<String> = [] {
|
|
didSet { persistSeenBugs() }
|
|
}
|
|
|
|
private init() {
|
|
if let data = UserDefaults.standard.data(forKey: configKey),
|
|
let config = try? JSONDecoder().decode(AppConfig.self, from: data) {
|
|
self.config = config
|
|
}
|
|
if let data = UserDefaults.standard.data(forKey: seenBugsKey),
|
|
let ids = try? JSONDecoder().decode(Set<String>.self, from: data) {
|
|
self.persistedSeenBugs = ids
|
|
}
|
|
}
|
|
|
|
func saveConfig(_ config: AppConfig) {
|
|
self.config = config
|
|
}
|
|
|
|
func updateSeenBugs(_ ids: Set<String>) {
|
|
persistedSeenBugs = ids
|
|
}
|
|
|
|
private func persistConfig() {
|
|
guard let config,
|
|
let data = try? JSONEncoder().encode(config) else {
|
|
return
|
|
}
|
|
UserDefaults.standard.set(data, forKey: configKey)
|
|
}
|
|
|
|
private func persistSeenBugs() {
|
|
guard let data = try? JSONEncoder().encode(persistedSeenBugs) else {
|
|
return
|
|
}
|
|
UserDefaults.standard.set(data, forKey: seenBugsKey)
|
|
}
|
|
}
|