CoderGirl
CoderGirl

Reputation: 13

How do I use DatePicker to schedule local notifications in Swift?

I am fairly new to iOS development. I thought it would be cool to use the DatePicker to schedule local notifications for an app I'm making.

I have @Binding var date = Date() initialized as the variable that will hold the user input from the DatePicker("Enter a date", $date). I thought that I could set up the DatePicker in the struct that I am using for the SwiftUI components and pass the date to the function scheduleNotification() located in the NotificationManager class (Like I said I'm new so if this is a bad idea please say so).

class NotificationManager {
    static let instance = NotificationManager()

    //function that handles authorizing the notification.
    func scheduleNotification(date: Date) {
        let content = UNMutableNotificationContent()
        content.title = "This is my first notification!"
        content.subtitle = "text"
        content.sound = .default
        content.badge = 1

        //What I did to extract the components from the variable
        let comps = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: date)

        //This is where I'm unclear what to do. I have seen on tutorials where the DateComponents() gets initialized and the .hour, .weekday, etc. gets individually assigned in military time for the notification. How do I handle that in this situation?

        //The trigger for the notification
        let trigger = UNCalendarNotificationTrigger(dateMatching: comps, repeats: true) //This is problematic code. In some of my attempts at this I get an error that says "Extra arguments at positions #1, #2 in call" and "Missing argument for parameter 'coder' in call" and "insert 'coder: <#NSCoder#>'" Do I need to do anything with NSCoder for this to work? Or is that error related to my not setting up the date compontents correctly like I mentioned before?

        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request)
    }
}

I have checked all over the Internet for support and haven't much luck. I have been playing around with it but am still stuck.

Upvotes: 0

Views: 84

Answers (0)

Related Questions