another.im-ios/AnotherIM/AppData/Services/PersistUserSettings.swift
2024-10-31 12:43:16 +01:00

62 lines
1.6 KiB
Swift

import Foundation
// Wrapper
@propertyWrapper
private struct Storage<T> {
private let key: String
private let defaultValue: T
init(key: String, defaultValue: T) {
self.key = key
self.defaultValue = defaultValue
}
var wrappedValue: T {
get {
// Read value from UserDefaults
UserDefaults.standard.object(forKey: key) as? T ?? defaultValue
}
set {
// Set value to UserDefaults
UserDefaults.standard.set(newValue, forKey: key)
UserDefaults.standard.synchronize()
}
}
}
// Storage
private let kBase = "conversations.classic.user.defaults"
private let kOmemoDevicesIds = "\(kBase).omemoDevicesIds"
private let kSecureChatsByDefault = "\(kBase).secureChatsByDefault"
enum UserSettings {
@Storage(key: kOmemoDevicesIds, defaultValue: [:])
private static var omemoDevicesIds: [String: UInt32]
@Storage(key: kSecureChatsByDefault, defaultValue: true)
private static var vSecureChatsByDefault: Bool
}
// Public
extension UserSettings {
static func reset() {
omemoDevicesIds = [:]
vSecureChatsByDefault = true
}
static func set(omemoDeviceId: UInt32, for account: String) {
var dict = UserSettings.omemoDevicesIds
dict[account] = omemoDeviceId
UserSettings.omemoDevicesIds = dict
}
static func get(omemoDeviceIdFor account: String) -> UInt32 {
UserSettings.omemoDevicesIds[account] ?? 0
}
static var secureChatsByDefault: Bool {
get { UserSettings.vSecureChatsByDefault }
set { UserSettings.vSecureChatsByDefault = newValue }
}
}