-
Notifications
You must be signed in to change notification settings - Fork 0
/
DataModel.swift
97 lines (79 loc) · 2.65 KB
/
DataModel.swift
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
//
// DataModel.swift
// Checklists
//
// Created by Micah on 2/18/22.
//
import Foundation
class DataModel {
var lists = [Checklist]()
var indexOfSelectedChecklist: Int {
get { return UserDefaults.standard.integer(forKey: "ChecklistIndex") }
set { UserDefaults.standard.set(newValue, forKey: "ChecklistIndex") }
}
init() {
loadChecklists()
registerDefaults()
handleFirstTime()
}
func registerDefaults() {
let dictionary = ["ChecklistIndex": -1, "FirstTime": true] as [String: Any]
UserDefaults.standard.register(defaults: dictionary)
}
func handleFirstTime() {
let userDefaults = UserDefaults.standard
let firstTime = userDefaults.bool(forKey: "FirstTime")
if firstTime {
let checklist = Checklist(name: "List")
lists.append(checklist)
indexOfSelectedChecklist = 0
userDefaults.set(false, forKey: "FirstTime")
}
}
// MARK: - Sorting
func sortChecklists() {
lists.sort { list1, list2 in return list1.name.localizedStandardCompare(list2.name) == .orderedAscending }
}
// MARK: - Data Saving
func documentsDirectory() -> URL {
let paths = FileManager.default.urls(
for: .documentDirectory,
in: .userDomainMask)
return paths[0]
}
func dataFilePath() -> URL {
return documentsDirectory().appendingPathComponent("Checklists.plist")
}
func saveChecklists() {
let encoder = PropertyListEncoder()
do {
let data = try encoder.encode(lists)
try data.write(
to: dataFilePath(),
options: Data.WritingOptions.atomic)
} catch {
print("Error encoding list array: \(error.localizedDescription)")
}
}
func loadChecklists() {
let path = dataFilePath()
if let data = try? Data(contentsOf: path) {
let decoder = PropertyListDecoder()
do {
lists = try decoder.decode(
[Checklist].self,
from: data)
sortChecklists()
} catch {
print("Error decoding list array: \(error.localizedDescription)")
}
}
}
// MARK: - Notifications
class func nextChecklistItemID() -> Int {
let userDefaults = UserDefaults.standard
let itemID = userDefaults.integer(forKey: "ChecklistItemID")
userDefaults.set(itemID + 1, forKey: "ChecklistItemID")
return itemID
}
}