0

I'm trying to find out how to update the message in the local notifications when it is repeated daily.

Currently I have the following code in my AppDelegate:

func scheduler(at date: Date, numOfNotes: Int)
{
    let calendar = Calendar(identifier: .gregorian)

    let components = calendar.dateComponents(in: .current, from: date)

    let newComponents = DateComponents(calendar: calendar, timeZone: .current, hour: components.hour, minute: components.minute)

    let trigger = UNCalendarNotificationTrigger(dateMatching: newComponents, repeats: true)

    content.badge = numOfNotes as NSNumber

    content.body = "REMINDER: " + String(numOfNotes) + " needs to be looked at!"

    content.sound = UNNotificationSound.default()

    let request = UNNotificationRequest(identifier: "reminderNotification", content: content, trigger: trigger)

    UNUserNotificationCenter.current().delegate = self

    UNUserNotificationCenter.current().add(request) {(error) in

    }
}

I am storing numOfNotes in UserDefaults. I have a UISwitch in my UITableViewCell, that upon being switched on calls the scheduler function like so:

func remindMeSwitch(_ remindMeSwitch: UISwitch)
{   
    numOfNotes = UserDefaults.standard.integer(forKey: "Notes")

    let delegate = UIApplication.shared.delegate as? AppDelegate

    delegate?.scheduler(at: time, numOfNotes: numOfNotes)
}

However, when setting the repeats parameter to true to have the notification repeat daily at the specified time, numOfNotes is only called once, which is when I toggle the UISwitch on.

How can I set the notification to alert daily but still be able to update the notification message as needed?

Thanks.

Pangu
  • 3,721
  • 11
  • 53
  • 120
  • 1
    It would seems that you'd need to schedule individual non-repeating notifications with appropriate messages to achieve this. – Losiowaty Apr 12 '17 at 05:47
  • @Losiowaty, i'd suspect that was the case but i was hoping to not have to re-schedule every time the count changes – Pangu Apr 12 '17 at 05:49
  • You can try adding a notification service app extension, but I'm not sure if it is called for local notifications. Also its available only from iOS 10. – Losiowaty Apr 12 '17 at 05:55

1 Answers1

0

In general, you don't have any possibility to change Local Notifications. Only one way - delete/cancel the old notification and create the new notification. But you can use a copy function.

For example, if you want to change the notification's content:

// create new content (based on old)
if let content = notificationRequest.content.mutableCopy() as? UNMutableNotificationContent {
    // any changes    
    content.title = "your new content's title"
    // create new notification
    let request = UNNotificationRequest(identifier: notificationRequest.identifier, content: content, trigger: notificationRequest.trigger)
    UNUserNotificationCenter.current().add(request)
}
Antony Karpov
  • 131
  • 1
  • 5