Gemini/Gemini-iOS/Preferences.swift

94 lines
2.9 KiB
Swift

//
// Preferences.swift
// Gemini-iOS
//
// Created by Shadowfacts on 9/27/20.
//
import UIKit
class Preferences: Codable, ObservableObject {
static let shared: Preferences = load()
private static var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
private static var archiveURL = Preferences.documentsDirectory.appendingPathComponent("Preferences").appendingPathExtension("plist")
static func save() {
let encoder = PropertyListEncoder()
let data = try? encoder.encode(shared)
try? data?.write(to: archiveURL, options: .noFileProtection)
}
static func load() -> Preferences {
let decoder = PropertyListDecoder()
if let data = try? Data(contentsOf: archiveURL),
let prefs = try? decoder.decode(Preferences.self, from: data) {
return prefs
}
return Preferences()
}
private init() {}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let stored = try container.decodeIfPresent(URL.self, forKey: .homepage) {
homepage = stored
}
theme = try container.decode(UIUserInterfaceStyle.self, forKey: .theme)
if let stored = try container.decodeIfPresent(Bool.self, forKey: .showLinkIcons) {
showLinkIcons = stored
}
useInAppSafari = try container.decode(Bool.self, forKey: .useInAppSafari)
useReaderMode = try container.decode(Bool.self, forKey: .useReaderMode)
if let stored = try container.decodeIfPresent(Bool.self, forKey: .hideToolbarsWhenScrolling) {
hideToolbarsWhenScrolling = stored
}
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(homepage, forKey: .homepage)
try container.encode(theme, forKey: .theme)
try container.encode(showLinkIcons, forKey: .showLinkIcons)
try container.encode(useInAppSafari, forKey: .useInAppSafari)
try container.encode(useReaderMode, forKey: .useReaderMode)
try container.encode(hideToolbarsWhenScrolling, forKey: .hideToolbarsWhenScrolling)
}
@Published var homepage = AppDelegate.defaultHomepage
@Published var theme = UIUserInterfaceStyle.unspecified
@Published var showLinkIcons = true
@Published var useInAppSafari = false
@Published var useReaderMode = false
@Published var hideToolbarsWhenScrolling = true
enum CodingKeys: String, CodingKey {
case homepage
case theme
case showLinkIcons
case useInAppSafari
case useReaderMode
case hideToolbarsWhenScrolling
}
}
extension UIUserInterfaceStyle: Codable {}