0

I'm trying to use a DatePicker to select a specific time of day, then once that time is selected, save the time as an ObservedObject and save it to my UserDefaults using SwiftUI. The problem with my code below is that while the data gets saved after the initial setting of the time, if the time is changed, that update does not show up in my DatePicker object like I am expecting it to. Can anyone help see what I'm doing wrong with my code here:

UserData.swift

import SwiftUI

class UserData: ObservableObject {

@Published var wakeUpTime: Date = UserDefaults.standard.object(forKey: "wakeUpTime") as? Date ?? Date() {
        didSet {
            UserDefaults.standard.set(self.wakeUpTime, forKey: "wakeUpTime")
        }
    }
}

AlarmSettingsView.swift

import SwiftUI

struct AlarmSettingsView: View {
    static var dateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "hh:mm a"
        return formatter
    }()

    @ObservedObject var userData = UserData()

    var body: some View {
        VStack {
            Text("\(self.userData.wakeUpTime, formatter: AlarmSettingsView.self.dateFormatter)")
            DatePicker("Please enter time.", selection: $userData.wakeUpTime, displayedComponents: .hourAndMinute)
                .labelsHidden()
        }
    }
}
Mac3n
  • 4,189
  • 3
  • 16
  • 29
Jason Rueckert
  • 661
  • 2
  • 6
  • 14
  • When a user changes the time with the picker is what I meant to convey. So how might I change it so that the time being saved in UserDefaults gets updated when a user changes the time using the DatePicker? – Jason Rueckert Mar 21 '20 at 16:34
  • Found the answer here: https://stackoverflow.com/a/59039333/1822779 – Jason Rueckert Mar 22 '20 at 04:58

0 Answers0