summaryrefslogtreecommitdiff
path: root/octosentry/PersistenceStore.swift
blob: ca86eec7ad08b2a9cbb9021ff00cb514e048cf79 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//
//  PersistenceStore.swift
//  octosentry
//
//  Loads and saves PersistedState as JSON in the app's Application Support
//  container. No entitlement needed — sandboxed apps always get a private
//  Application Support directory in their own container.
//

import Foundation

actor PersistenceStore {
    private let fileURL: URL

    private static let decoder: JSONDecoder = {
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .iso8601
        return decoder
    }()

    private static let encoder: JSONEncoder = {
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        return encoder
    }()

    init() {
        let appSupport = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
        let directory = appSupport.appendingPathComponent("octosentry", isDirectory: true)
        try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
        fileURL = directory.appendingPathComponent("state.json")
    }

    func load() -> PersistedState {
        guard let data = try? Data(contentsOf: fileURL),
              let state = try? Self.decoder.decode(PersistedState.self, from: data) else {
            return .placeholder
        }
        return state
    }

    func save(_ state: PersistedState) {
        guard let data = try? Self.encoder.encode(state) else { return }
        try? data.write(to: fileURL, options: .atomic)
    }
}