parent
efa89c4d3d
commit
644616784a
@ -0,0 +1,54 @@
|
||||
//
|
||||
// UnitsStore.swift
|
||||
// Graduator
|
||||
//
|
||||
// Created by etudiant on 2023-06-10.
|
||||
//
|
||||
|
||||
import SwiftUI
|
||||
|
||||
|
||||
class UnitsStore: ObservableObject {
|
||||
|
||||
var units: [Unit] = []
|
||||
|
||||
private static func fileURL() throws -> URL {
|
||||
try FileManager.default.url(
|
||||
for: .documentDirectory,
|
||||
in: .userDomainMask,
|
||||
appropriateFor: nil,
|
||||
create: false
|
||||
).appendingPathComponent("units.data")
|
||||
}
|
||||
|
||||
func load() async throws -> [Unit] {
|
||||
|
||||
let task = Task<[Unit], Error> {
|
||||
let fileURL = try Self.fileURL()
|
||||
let data = try? Data(contentsOf: fileURL)
|
||||
var units: [Unit] = []
|
||||
if (data == nil || data!.isEmpty) {
|
||||
units = Stub.units
|
||||
}
|
||||
else if (data != nil) {
|
||||
units = try JSONDecoder().decode([Unit].self, from: data!)
|
||||
}
|
||||
return units
|
||||
}
|
||||
|
||||
self.units = try await task.value
|
||||
return self.units
|
||||
}
|
||||
|
||||
func save(units: [Unit]) async throws {
|
||||
|
||||
let task = Task {
|
||||
let data = try JSONEncoder().encode(units)
|
||||
let outfile = try Self.fileURL()
|
||||
try data.write(to: outfile)
|
||||
}
|
||||
|
||||
_ = try await task.value
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in new issue