persist stopwatches
This commit is contained in:
@@ -11,14 +11,22 @@ import Combine
|
||||
class ContentViewModel: ObservableObject {
|
||||
@Published var stopwatches: [Stopwatch] = []
|
||||
|
||||
private let saveKey = "SavedStopwatches"
|
||||
|
||||
init() {
|
||||
load()
|
||||
}
|
||||
|
||||
func addStopwatch(name: String) {
|
||||
let newStopwatch = Stopwatch(name: name)
|
||||
stopwatches.append(newStopwatch)
|
||||
save()
|
||||
}
|
||||
|
||||
func deleteStopwatch(at index: Int) {
|
||||
stopwatches[index].pause() // Ensure timer is stopped
|
||||
stopwatches.remove(at: index)
|
||||
save()
|
||||
}
|
||||
|
||||
func deleteStopwatch(id: UUID) {
|
||||
@@ -26,11 +34,26 @@ class ContentViewModel: ObservableObject {
|
||||
deleteStopwatch(at: index)
|
||||
}
|
||||
}
|
||||
|
||||
func save() {
|
||||
if let encoded = try? JSONEncoder().encode(stopwatches) {
|
||||
UserDefaults.standard.set(encoded, forKey: saveKey)
|
||||
}
|
||||
}
|
||||
|
||||
func load() {
|
||||
if let data = UserDefaults.standard.data(forKey: saveKey) {
|
||||
if let decoded = try? JSONDecoder().decode([Stopwatch].self, from: data) {
|
||||
stopwatches = decoded
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct ContentView: View {
|
||||
@StateObject private var viewModel = ContentViewModel()
|
||||
@State private var isShowingAddSheet = false
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
var body: some View {
|
||||
NavigationStack {
|
||||
@@ -73,6 +96,11 @@ struct ContentView: View {
|
||||
}
|
||||
}
|
||||
}
|
||||
.onChange(of: scenePhase) { newPhase in
|
||||
if newPhase == .background || newPhase == .inactive {
|
||||
viewModel.save()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user