From e55736d4d557394598e2d10af06afd0760cb7847 Mon Sep 17 00:00:00 2001 From: Aaron Date: Tue, 26 Jan 2021 22:18:18 -0500 Subject: [PATCH] Editing an alarm now reschedules the notification --- ProjectClock/AddAlarmViewController.swift | 14 +++++++++----- ProjectClock/Notification.swift | 12 ++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/ProjectClock/AddAlarmViewController.swift b/ProjectClock/AddAlarmViewController.swift index f310c3b..472c131 100644 --- a/ProjectClock/AddAlarmViewController.swift +++ b/ProjectClock/AddAlarmViewController.swift @@ -83,8 +83,9 @@ class AddAlarmViewController: UIViewController /** Removes the currently selcted alarm. + Returns the removed Alarm object. */ - func removeCurrentAlarm() { + func removeCurrentAlarm() -> Alarm? { let hours = Int(String(originalTime[...originalTime.index(originalTime.endIndex, offsetBy: -4 )]))! let minutes = Int(String(originalTime.suffix(2)))! @@ -95,6 +96,8 @@ class AddAlarmViewController: UIViewController let alarmsObj = Alarms.fromLocal() alarmsObj.list = Alarms.fromLocal().list.filter { $0 != alarm } alarmsObj.localSave() + + return alarm } /** @@ -124,13 +127,12 @@ class AddAlarmViewController: UIViewController @IBAction func addAlarmButton(_ sender: Any) { let (h, m, _) = timePicker.date.getHMS() + var oldAlarm: Alarm? = nil // Check if editing alarm if (editFlag) { - removeCurrentAlarm() - - + oldAlarm = removeCurrentAlarm() } // Check for existing alarm else if ((Alarms.fromLocal().list.contains { $0.hour == h && $0.minute == m })) { @@ -153,6 +155,9 @@ class AddAlarmViewController: UIViewController Alarms.fromLocal().apply { $0.list.append(alarm) }.localSave(); //Schedules notification for the alarm + if editFlag{ + Notification(alarm: oldAlarm!).removeNotification() + } Notification(alarm: alarm).scheduleNotification() // Dismiss this view @@ -177,7 +182,6 @@ class AddAlarmViewController: UIViewController if repeatWeekendsSwitch.isOn { [0, 6].forEach { a.repeats[$0] = true } } let timeTill = a.nextActivate!.timeIntervalSince(Date()).str() - //print(timeTill) timeTillAlarmLabel.text = "Going off in \(timeTill)" } diff --git a/ProjectClock/Notification.swift b/ProjectClock/Notification.swift index cfbeee5..50afc7d 100644 --- a/ProjectClock/Notification.swift +++ b/ProjectClock/Notification.swift @@ -16,6 +16,18 @@ class Notification { var alarm: Alarm + func removeNotification() { + UNUserNotificationCenter.current().getPendingNotificationRequests { (notificationRequests) in + var identifiers: [String] = [] + for notification:UNNotificationRequest in notificationRequests { + if notification.identifier == self.alarm.notificationID { + identifiers.append(notification.identifier) + } + } + UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers) + } + } + func scheduleNotification() { let content = UNMutableNotificationContent()