frenzy-ios/Reader/LocalData.swift

68 lines
1.8 KiB
Swift
Raw Normal View History

2021-12-08 02:58:02 +00:00
//
// 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()
2022-01-12 18:48:52 +00:00
static var accounts: [Account] {
2021-12-08 02:58:02 +00:00
get {
2022-01-12 18:48:52 +00:00
guard let data = UserDefaults.standard.data(forKey: "accounts"),
let accounts = try? decoder.decode([Account].self, from: data) else {
return []
2021-12-08 02:58:02 +00:00
}
2022-01-12 18:48:52 +00:00
return accounts
2021-12-08 02:58:02 +00:00
}
set {
let data = try! encoder.encode(newValue)
2022-01-12 18:48:52 +00:00
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
2021-12-08 02:58:02 +00:00
}
2022-01-12 18:48:52 +00:00
return accounts.first(where: { $0.id == id })
2021-12-08 02:58:02 +00:00
}
struct Account: Codable {
2021-12-25 19:04:45 +00:00
let id: UUID
2021-12-08 02:58:02 +00:00
let instanceURL: URL
let clientID: String
let clientSecret: String
let accessToken: String
// todo: refresh tokens
2021-12-25 19:04:45 +00:00
init(instanceURL: URL, clientID: String, clientSecret: String, accessToken: String) {
self.id = UUID()
self.instanceURL = instanceURL
self.clientID = clientID
self.clientSecret = clientSecret
self.accessToken = accessToken
}
2021-12-08 02:58:02 +00:00
}
}