-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSharedData.swift
More file actions
76 lines (65 loc) · 2.21 KB
/
SharedData.swift
File metadata and controls
76 lines (65 loc) · 2.21 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
//
// SharedData.swift
// JRNL
//
// Created by iOS17Programming on 23/10/2023.
//
import UIKit
class SharedData {
// MARK: - Properties
static let shared = SharedData()
private var journalEntries: [JournalEntry]
// MARK: - Private
private init() {
journalEntries = []
}
// MARK: - Access methods
func numberOfJournalEntries() -> Int {
journalEntries.count
}
func getJournalEntry(index: Int) -> JournalEntry {
journalEntries[index]
}
func getAllJournalEntries() -> [JournalEntry] {
let readOnlyJournalEntries = journalEntries
return readOnlyJournalEntries
}
func addJournalEntry(newJournalEntry: JournalEntry) {
journalEntries.append(newJournalEntry)
}
func removeJournalEntry(index: Int) {
journalEntries.remove(at: index)
}
func removeSelectedJournalEntry(_ selectedJournalEntry: JournalEntry) {
journalEntries.removeAll() {
$0.key == selectedJournalEntry.key
}
}
// MARK: - Persistence
func getDocumentDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return paths[0]
}
func loadJournalEntriesData() {
let pathDirectory = getDocumentDirectory()
let fileURL = pathDirectory.appendingPathComponent("journalEntriesData.json")
do {
let data = try Data(contentsOf: fileURL)
let journalEntriesData = try JSONDecoder().decode([JournalEntry].self, from: data)
journalEntries = journalEntriesData
} catch {
print("Failed to read JSON data: \(error.localizedDescription)")
}
}
func saveJournalEntriesData() {
let pathDirectory = getDocumentDirectory()
try? FileManager().createDirectory(at: pathDirectory, withIntermediateDirectories: true)
let filePath = pathDirectory.appendingPathComponent("journalEntriesData.json")
let json = try? JSONEncoder().encode(journalEntries)
do {
try json!.write(to: filePath)
} catch {
print("Failed to write JSON data: \(error.localizedDescription)")
}
}
}