frenzy-ios/Reader/LocalData.swift

68 lines
1.8 KiB
Swift

//
// LocalData.swift
// Reader
//
// Created by Shadowfacts on 11/25/21.
//
import Foundation
struct LocalData {
private init() {}
private static let encoder = JSONEncoder()
private static let decoder = JSONDecoder()
static var accounts: [Account] {
get {
guard let data = UserDefaults.standard.data(forKey: "accounts"),
let accounts = try? decoder.decode([Account].self, from: data) else {
return []
}
return accounts
}
set {
let data = try! encoder.encode(newValue)
UserDefaults.standard.set(data, forKey: "accounts")
}
}
static var mostRecentAccountID: UUID? {
get {
guard let str = UserDefaults.standard.string(forKey: "mostRecentAccountID") else {
return nil
}
return UUID(uuidString: str)
}
set {
UserDefaults.standard.set(newValue?.uuidString, forKey: "mostRecentAccountID")
}
}
static func mostRecentAccount() -> Account? {
guard let id = mostRecentAccountID else {
return nil
}
return accounts.first(where: { $0.id == id })
}
struct Account: Codable {
let id: UUID
let instanceURL: URL
let clientID: String
let clientSecret: String
let accessToken: String
// todo: refresh tokens
init(instanceURL: URL, clientID: String, clientSecret: String, accessToken: String) {
self.id = UUID()
self.instanceURL = instanceURL
self.clientID = clientID
self.clientSecret = clientSecret
self.accessToken = accessToken
}
}
}