1
votes

I am adding a local notification feature to my iOS app which will fire up a notification / alert on a specified time e.g. 7am daily. So I setup the alert using the code below:

    let content = UNMutableNotificationContent()
    content.title = "Planned transactions due today"
    content.body = "You have [NUMBER] scheduled income and [NUMBER] planned expenses due for today."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default
    
    let date = Date(hour: 7, minute: 0, second: 0) //custom initializer from Date extension
    let dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

    let request = UNNotificationRequest(identifier: "Reminder", content: content, trigger: trigger)
    
    center.add(request) { (error) in
        if let error = error {
            print("Error scheduling notification: \(error.localizedDescription)")
        }
    }

It works perfectly. But what I want to achieve is to add more useful information within the local notification's body, like replacing the [NUMBER] to an actual number which is derrived from a query from core data.

I need help on how to pull this off. I've looked at implementations using UNNotificationServiceExtension and UNNotificationContentExtension. But I can't seem to make it work. I was unable to find any implementations of UNNotificationServiceExtension that applies to local notification – I could be wrong but I think it's only for push notifications.

I've also tried implementing UNUserNotificationCenterDelegate on the AppDelegate to intercept the notification as it is being triggered. func userNotificationCenter(willPresent:) method allows me to get the notification but there seems to be no way for me to change the .content property as it is get-only.

So basically, I just want to be able to change the body content of the notification before it is being displayed.

Hope that was clear :-)

Thank you in advance!

1
Question is very well explained, I think there is no way to do it for the local notification. And you are right 'UNNotificationServiceExtension' will only work with remote notification. Last option is remote notification .You can check this for more details. developer.apple.com/documentation/usernotifications/…Bhavin Vaghela

1 Answers

0
votes

My solution isn't the best, but to achive this, i do the following at each app launch: first cancel the next notifications, then update it with a new content. It works fine if the app is used at a regular basis.

there is some something called BGTaskScheduler. Apple said that it is a

A class for scheduling task requests that launch your app in the background. https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler

Maybe you should check for it