forked from Jaysce/Spaceman
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPreferencesViewModel.swift
More file actions
74 lines (61 loc) · 1.95 KB
/
Copy pathPreferencesViewModel.swift
File metadata and controls
74 lines (61 loc) · 1.95 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
//
// PreferencesViewModel.swift
// Spaceman
//
// Created by Sasindu Jayasinghe on 6/12/20.
//
import Foundation
import Observation
@MainActor
@Observable
final class PreferencesViewModel {
var selectedSpace = 0
var spaceName = ""
var spaceNamesDict: [String: SpaceNameInfo] = [:]
var sortedSpaceNamesDict: [Dictionary<String, SpaceNameInfo>.Element] = []
@ObservationIgnored private var timer: Timer?
init() {
if UserDefaults.standard.bool(forKey: "autoRefreshSpaces") {
startTimer()
}
}
deinit {
timer?.invalidate()
}
func loadData() {
guard let data = UserDefaults.standard.value(forKey: "spaceNames") as? Data else {
return
}
self.selectedSpace = 0
guard let decoded = try? PropertyListDecoder().decode([String: SpaceNameInfo].self, from: data) else {
Log.preferences.error("Failed to decode spaceNames; keeping previous state")
return
}
self.spaceNamesDict = decoded
let sorted = spaceNamesDict.sorted { first, second in
first.value.spaceNum < second.value.spaceNum
}
sortedSpaceNamesDict = sorted
}
func updateSpace() {
let key = sortedSpaceNamesDict[selectedSpace].key
let spaceNum = sortedSpaceNamesDict[selectedSpace].value.spaceNum
spaceNamesDict[key] = SpaceNameInfo(spaceNum: spaceNum, spaceName: spaceName.isEmpty ? "N/A" : spaceName)
}
func startTimer() {
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { [weak self] _ in
Task { @MainActor in
self?.refreshSpaces()
}
}
}
func pauseTimer() {
timer?.invalidate()
timer = nil
}
private func refreshSpaces() {
Log.preferences.debug("Periodic refresh tick")
NotificationCenter.default.post(name: .spacemanRefresh, object: nil)
}
}