IOS trigger notification action when app is in the background

Viewed 114

My app does the following when the app is opened from a remote notification. Basically, it saves article_id in UserDefaults so that I can use it when the app is launched:

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(
        _ center: UNUserNotificationCenter,
        didReceive response: UNNotificationResponse,
        withCompletionHandler completionHandler: @escaping () -> Void
    ) {
        let userInfo = response.notification.request.content.userInfo
        
        if let aps = userInfo["aps"] as? [String: AnyObject] {

            let article_id = aps["article_id"]
            UserDefaults.standard.set(article_id, forKey: "notification_article_id")
        }

        completionHandler()
    }
}

However, this only works if the app is completely closed. If the app remains in the background and the user clicks the notification (e.g. from the lock screen), the function above will not be triggered. Thus, it will not save the data into my UserDefaults. Does any one know how to trigger a similar action in this situation? Thanks in advance!

1 Answers

Your extension delegate function declaration is correct, and should fire in the state that you described (lock screen, home screen, app backgrounded). Please make sure that you have set the delegate:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  UNUserNotificationCenter.current().delegate = self

}

If this is already set, I would verify that your parsing code is correct, and test on the simulator or another device. I often use xcrun simctl to test push notifications in the simulator. You can do this by creating a dummy test file called 'payload.json', and exectuting the following command in the terminal:

xcrun simctl push booted com.yourapp.bundle.id payload.json

This is an example of a payload.json:

{
    "Simulator Target Bundle": "com.yourapp.bundle.id",
    "aps":{
        "alert":{
            "title":"Egon Spengler",
            "body":"I collect spores, molds, and fungus"
        },
        "sound":"alert.caf",
        "badge":3
    },
    "alert":{
        "alertUuid":"asdfasdfasdfasdfasdf",
        "state":1,
        "lastUpdate":"2020-11-8T21:43:57+0000"
    }
}

If the application has been terminated, you can obtain notification content at launch using the following code within didFinishLaunchingWithOptions:

 let notificationOption = launchOptions?[.remoteNotification]
 if let notification = notificationOption as? [String: AnyObject] {
           
 } 

Finally, make sure that you have enabled 'Remote Notifications' background mode in your project settings:

Background Modes

Related