iOS: Do something when a UserNotification is received?

425 Views Asked by At

Is it possible to do something when the UserNotification message is delivered to the user every time?

 let tdate = Date(timeIntervalSinceNow: 10)
    let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: tdate)
    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: true)

    let identifier = "hk.edu.polyu.addiction.test"
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
      if error != nil {
        debugPrint("center.add(request, withCompletionHandler: { (error)")
      } else {
        debugPrint("no error?! at request added place")
      }
    })

This is the code i did to deliver a notification when the user press a button. (i.e., after 10s, the notification appear to the user.)

Even the user not press on the notification, i want some variable of the app updated (assume the app is at the background).

Possible?

Or, as long as this notification is done. another new notification is scheduled, according to some calculations in my app, possible? (not fixed time, cannot use repeat)

1

There are 1 best solutions below

5
On

Yes, it is possible! Need to modify the capabilities :

  1. Enable background fetch in background mode.
  2. Enable remote notification in background mode.
  3. Implement delegate method : application:didReceiveRemoteNotification:fetchCompletionHandler:
  4. This delegate method gets called when the notification arrives on the phone, so you can refresh your data.
  5. When user taps on notification delegate method: didReceiveRemoteNotification gets called and opens the app and user will get latest data in the app.

Apple API reference:

If your payload is not configured properly, the notification might be displayed to the user instead of being delivered to your app in the background. In your payload, make sure the following conditions are true:

The payload’s aps dictionary must include the content-available key with a value of 1. The payload’s aps dictionary must not contain the alert, sound, or badge keys. When a silent notification is delivered to the user’s device, iOS wakes up your app in the background and gives it up to 30 seconds to run.