Search code examples
iosswiftswiftuiswiftui-environmentswiftui-form

How to show alert message in swiftUI when user enters time below the expected time?


I'm building an alarm kinda app and I just want to display a pop up message (alert message) when user enter time below 2 hours, the user should get a message by saying like, "please enter time more than 2 hours of duration".

This is where I stored the alarm value

myViewModel.myModel.waketime

and I want to display the message when a user click this below image

 Image(systemName: "checkmark.circle")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .clipShape(Circle())
                        .sheet(isPresented: $showPlayer) {
                            SecondView()
                        }

This is another view where the user picks the alarm time

 Text("Alarm : ")
  .font(.body)
   Spacer()
   DatePicker("", selection: self.$myViewModel.myModel.waketime, displayedComponents: .hourAndMinute)

Please help me to solve this!!


Solution

  • You can use Alert to show an alert to the user. In order to do this when the user clicks on the Image, you'd probably want to wrap it in a Button:

    struct ContentView : View {
        @State var alertShown = false
        
        var body: some View {
            Button(action: {
                if true { //here, you can check your condition for whether the alert should get triggered -- like checking `myViewModel.myModel.waketime > x`
                    alertShown = true
                }
            }) {
                Image(systemName: "checkmark.circle")
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .clipShape(Circle())
            }.alert(isPresented: $alertShown) {
                Alert(title: Text("Please enter time more than 2 hours of duration"))
            }
        }
    }
    

    You may want to add .buttonStyle(PlainButtonStyle()) as a modifier to the Button if you don't want it to change your Image to the accentColor in your project.

    Update in response to comments: The general check you'd want to do is:

    if myViewModel.myModel.waketime.timeIntervalSince1970 - Date().timeIntervalSince1970 < 60 * 60 * 2 {
    

    However, be aware that with your current strategy of only showing hours and minutes, this will start to fail at 2 hours before midnight, since the DatePicker will default to the current date, making 1 AM, for example, register as before the current date/time, not after. So, you'll want to add some additional logic to account for things like that. For example, you could add 24 hours to any time before the current date.