forked from shadowfacts/Tusker
55 lines
1.5 KiB
Swift
55 lines
1.5 KiB
Swift
//
|
|
// DraftsManager.swift
|
|
// Tusker
|
|
//
|
|
// Created by Shadowfacts on 10/22/18.
|
|
// Copyright © 2018 Shadowfacts. All rights reserved.
|
|
//
|
|
|
|
import Foundation
|
|
|
|
class DraftsManager: Codable {
|
|
|
|
private(set) static var shared: DraftsManager = load()
|
|
|
|
private static var documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
|
|
private static var archiveURL = DraftsManager.documentsDirectory.appendingPathComponent("drafts").appendingPathExtension("plist")
|
|
|
|
static func save() {
|
|
DispatchQueue.global(qos: .utility).async {
|
|
let encoder = PropertyListEncoder()
|
|
let data = try? encoder.encode(shared)
|
|
try? data?.write(to: archiveURL, options: .noFileProtection)
|
|
}
|
|
}
|
|
|
|
static func load() -> DraftsManager {
|
|
let decoder = PropertyListDecoder()
|
|
if let data = try? Data(contentsOf: archiveURL),
|
|
let draftsManager = try? decoder.decode(DraftsManager.self, from: data) {
|
|
return draftsManager
|
|
}
|
|
return DraftsManager()
|
|
}
|
|
|
|
private init() {}
|
|
|
|
var drafts: [Draft] = []
|
|
var sorted: [Draft] {
|
|
return drafts.sorted(by: { $0.lastModified > $1.lastModified })
|
|
}
|
|
|
|
func add(_ draft: Draft) {
|
|
drafts.append(draft)
|
|
}
|
|
|
|
func remove(_ draft: Draft) {
|
|
drafts.removeAll { $0 == draft }
|
|
}
|
|
|
|
func getBy(id: UUID) -> Draft? {
|
|
return drafts.first { $0.id == id }
|
|
}
|
|
|
|
}
|