Schedule Notification to trigger at specific time - Swift

Viewed 861

In my app, I have a uidatepickerview that lets the user pick a time. Currently in my code I have that time selected passed as dateA. I then looped through all of the days that are selected in a separate uitableview, and checked to see if they were equal to today's day(such as Tuesday). If the days were the same, then I a notification would send at the selected time that was passed as dateA. However, when I try to send the notification, it is not sent.

Here is a snippet of my code showing what I have tried:

    var dateA: Date? = nil//where selected time is kept

    var weekdaysChecked = [String]()//where selected weekdays are kept

    var alarms = [Alarm]() {
        didSet {
            tableView.reloadData()
        }
    }


    override func viewDidLoad() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound], completionHandler: { (didAllow, error) in
        })

    }


    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "alarmCell", for: indexPath) as! DisplayAlarmCell

        let row = indexPath.row
        let alarm = alarms[row]
        let date = Date()
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat  = "EEEE"//"EE" to get short style
        let dayInWeek = dateFormatter.string(from: date)


        if(alarms.count == 40) {
            self.navigationItem.rightBarButtonItem?.isEnabled = false
            tableView.reloadData()
        }

        cell.alarmTitle.text = alarm.alarmLabel
        cell.clockTitle.text = alarm.time

        for weekdays in weekdaysChecked {
            if(dayInWeek == weekdays){
                let content = UNMutableNotificationContent()
                content.title = alarm.alarmLabel!
                content.subtitle = alarm.time!
                content.sound = UNNotificationSound(named: "Spaceship_Alarm.mp3")

                let trigger = Calendar.current.dateComponents([.hour,.minute], from: dateA!)
                let triggerNotif = UNCalendarNotificationTrigger(dateMatching: trigger, repeats: false)

                let triggerRequest = UNNotificationRequest(identifier: "AlarmNotif", content: content, trigger: triggerNotif)

                UNUserNotificationCenter.current().add(triggerRequest, withCompletionHandler: nil)

                print("This is the correct day.")
            }
        }
2 Answers
Related