Random Repeating Local Notifications in Swift

1.6k views Asked by At

TL;DR: Is it possible to have repeating, random local notifications without using APNS (or an alternative push notification service)?

I am building a Core Data app that includes a bunch of objects. (We'll call them widgets.) Every day at a certain time – let's say noon – I want to send a notification to check out one of these widgets.

In didFinishLaunchingWithOptions I check to make sure Notifications are enabled and set the delegate, etc. and call a function to build the local notification. All this is working perfectly.

    var date = DateComponents()
    date.hour = 12
    date.minute = 00
    let content = UNMutableNotificationContent()
    content.title = "You should see this widget!"
    content.userInfo = ["widgetID": widget.id]
    content.body = "Today's Widget:\n\(widget.title!)"
    content.sound = UNNotificationSound.default()
    let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)
    let request = UNNotificationRequest(identifier: notificationIdentifer, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error : Error?) in if let theError = error { print(theError.localizedDescription)}}

And I have the delegate's handler working correctly, too:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) { ... a bunch of stuff to happen ... }

As it is now, in that function I'm able to "reset" the UNMutableNotificationContent to a new random widget IF the user interacts with the notification in any explicit way. The problem is that if the user doesn't interact with the notification at all — see the "Handling the Standard System Actions" section of Apple's Scheduling and Handling Local Notifications documentation — I have no way to "reset" the notification, so tomorrow they're simply going to get suggested the same widget again, and that's annoying.

I'm not really interested in using APNS (or an alternative) because I don't feel like I should need to do that and don't want to deal with all the extra stuff required, but I cannot seem to find an alternative.

Please note that this question is not a duplicate of:

0

There are 0 answers