Search code examples
notificationsswiftuiios14

Swift UI 2.0: How can to set up this Notification?


First of all, I have never used notifications in an app. I have done tutorials but the whole thing confuses me.

I have created a SwiftUI file called Notify.swift. I want the user to be able to set a time for a notification to alert them to perform a task at a specified time, like in this image:

notify.swift file image

Where you see the time in the image, I have created a DatePicker to pick a time for the notification:

VStack {
    Button(action: {}) {
        HStack {
             DatePicker("   Select a time ....", 
                 selection: $wakeup, displayedComponents: .hourAndMinute)
                 .font(.title2)
                 .accentColor(Color(.white))
        }
    }.background(Color(.black))
}
.frame(width: .infinity, height: 40, alignment: .center)
.padding()

When the user clicks on the Create Button to set the notification, it should set the notification at that particular time (all the time, unless changed). This is what I need to happen but don't know how to do it:

If the notification time is set for 8:30am, like in the image, and the user selects CREATE, a notification is set and should be sent to the user to perform whatever task with maybe a sound and a message at that specified time.

I understand that there are different types of notification: local, user, Apple push, etc, but I don't know which type this falls in or how to do it.

Would this be a notification or an alarm?


Solution

  • You can use local notifications for that. Here I made a function for you to trigger the notification. First off all, check if that time is prior the current time. Then the notification will be tomorrow and we add one day to our Date. You can change title, body as you wish.

    Make sure to wrap your DatePicker outside the button, otherwise it will always trigger a notification when you click the DatePicker.

    func scheduleNotification() -> Void {
        let content = UNMutableNotificationContent()
        content.title = "Your title"
        content.body = "Your body"
        
        var reminderDate = wakeup
        
        if reminderDate < Date() {
            if let addedValue = Calendar.current.date(byAdding: .day, value: 1, to: reminderDate) {
                reminderDate = addedValue
            }
        }
    
        let comps = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: reminderDate)
                               
        let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: false)
        
        let request = UNNotificationRequest(identifier: "alertNotificationUnique", content: content, trigger: trigger)
    
         UNUserNotificationCenter.current().add(request) {(error) in
             if let error = error {
                 print("Uh oh! We had an error: \(error)")
             }
         }
    }
    

    Also you need to request permission for Notifications like this:

    func requestPush() -> Void {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                print("All set!")
            } else if let error = error {
                print(error.localizedDescription)
            }
        }
    }
    

    Here your button:

    VStack {
        Button(action: {
            scheduleNotification()
        }) {
            Text("Save notification")
        }
         DatePicker("Select a time ....",
             selection: $wakeup, displayedComponents: .hourAndMinute)
             .font(.title2)
             .accentColor(Color(.white))
    }