How to Perform an Action after User Tapped Notification

In my personal finance management App, when the user tap a push notification. I want to take the user directly to the account page, where the user will be able to update account balance directly.

I found it quite easy to acheve with UNUserNotificationCenter APIs.

The only thing I need to do is listen to this UNUserNotificationCenterDelegate callback event:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                            didReceive response: UNNotificationResponse,
                            withCompletionHandler completionHandler: @escaping () -> Void) {

    switch response.actionIdentifier {
    case UNNotificationDefaultActionIdentifier:
        // Get account with identifier
        // Open updateVC with this account
        log(.info, response.notification.request.identifier)
        delegate?.didReceiveNotification(with: response.notification.request.identifier)

    default:
        break
    }

    completionHandler()
}

Here the delegate is my view controller where I would implement the logic to take the user to a specific page.

The interesting thing is I made some mistakes until I find a good setup.

Mistake #1: I thought I would have to implement applicationDidReceiveNotification in AppDelegate.

But it turns out that UNUserNotificationCenter callback is the right way to go.

Mistake #2: In my view controller, I thought I will need a boolean to remember the callback id until my VC is fully setup to present another page

This boolean, pendingAccountIdToPresent: Bool in my case, is not necessary. Because in my main view controller, I would fetch data from Core Data in the same run loop as applicationDidFinishLaucnhing.

Because UNUserNotificationCenter send the notification callback in a later run loop, so my main view controller’s data will be ready when the callbacks fires. Therefore a boolean to remember the state is not necessary.

Here is the final result, a detail account page is shown after notification is tapped.

Posted 2020-03-01

More writing at jakehao.com