Search code examples
iosswiftuilocalnotification

How do I set up a repeating daily notification with different content each time?


I'm working on an app that gives you a notification at mid-day. This notification is supposed to be different every day.

I got the notifications themselves working:

let notificationOptions: UNAuthorizationOptions = [.alert, .sound];
UNUserNotificationCenter.current().requestAuthorization(options: notificationOptions) { (granted, error) in
    if !granted {
        print("Something went wrong")
    } else {
        let content = UNMutableNotificationContent()
        content.body = getRandomDailyString()
        content.sound = UNNotificationSound.default()

        let date = DateComponents(hour: 12, minute: 15)
        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

        let request = UNNotificationRequest(identifier: "Daily String", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print(error.localizedDescription)
            }
        }
    }
}

What's happening now is that the getRandomDailyString()-function is called, it returns a string, and a repeating notification is set which does appear the specified time, but always has the same content.

How would I go about making a notification that gives a unique content every day?


Solution

  • Ok, here is the solution for this.

    It is NOT possible to schedule a repeating notification with a random content each day. The content is defined when the notification is scheduled, and cannot be changed later.

    What you CAN do it schedule up to 64 notifications in advance though. So you can schedule 64 unique notifications for the next 64 days, and then whenever you open the app check how many remain, and fill up the notification-schedule up to 64 again.

    If you don't open the app after 64 days the notifications stop coming though :P