> ## Documentation Index
> Fetch the complete documentation index at: https://documentation.onesignal.com/llms.txt
> Use this file to discover all available pages before exploring further.

# v3-4 SDK SDK Notification Event Handlers

> Handling Notification Events within OneSignal

<Warning>
  The methods below require the OneSignal SDK versions 3 & 4.

  It is recommended to upgrade to our latest version 5 SDKs for User Model APIs.

  See [Update to User Model](/docs/en/user-model-migration-guide) for migration steps.
</Warning>

| Notification Events                                                                   | Details                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [**Foreground Notification Received Event**](#foreground-notification-received-event) | OneSignal SDK `setNotificationWillShowInForegroundHandler` method runs before displaying a notification while the app is in focus. Use this handler to decide if the notification should show or not.                                                                                                                                                                                                                                                                                                                                                                                                       |
| [**Notification Opened Event**](#notification-opened-event)                           | OneSignal SDK `setNotificationOpenedHandler` method runs upon opening the app after a notification is clicked.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| [**Background Notification Received Event**](#background-notification-received-event) | Native Methods that run while a notification is received while app is in the background. These methods require using Native Code like Java/Kotlin or Swift/Objective-C.                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| **Force-quit Notification Received Event**                                            | **iOS** - Force-quit state is when the app has been "swiped away" and not running in the foreground or background. Apple still keeps an open connection to your app but requires the [Service Extensions](/docs/en/service-extensions) for notification data detection. **Android** - Force-quit generally happens manually through the App Settings and prevents any communication to your app. Further, some OEMs will put your app into this force-quit state when swiping the app away. See [Notifications Not Shown](/docs/en/notifications-show-successful-but-are-not-being-shown) for more details. |

# Foreground Notification Received Event

## `setNotificationWillShowInForegroundHandler` Method

Runs before displaying a notification while the app is in focus. Use this handler to read notification data and change it or decide if the notification ***should*** show or not.

Call `setNotificationWillShowInForegroundHandler` before you set `OneSignal.setNotificationOpenedHandler`.

Note: this runs ***after*** the [Notification Service Extension](/docs/en/service-extensions) which can be used to modify the notification before showing it.

| Platform | Parameter                                   | Type     |
| -------- | ------------------------------------------- | -------- |
| Android  | `OSNotificationWillShowInForegroundHandler` | Callback |
| iOS      | `OSNotificationWillShowInForegroundBlock`   | Block    |

<CodeGroup>
  ```java java theme={null}
  OneSignal.setNotificationWillShowInForegroundHandler(new NotificationWillShowInForegroundHandler() {
     @Override
     void notificationWillShowInForeground(OSNotificationReceivedEvent notificationReceivedEvent) {
       OSNotification notification = notificationReceivedEvent.getNotification();
       // Get custom additional data you sent with the notification
       JSONObject data = notification.getAdditionalData();

       if (/* some condition */ ) {
          // Complete with a notification means it will show
          notificationReceivedEvent.complete(notification);
       }
       else {
         // Complete with null means don't show a notification
         notificationReceivedEvent.complete(null);
      }
    }
  });
  ```

  ```swift Swift theme={null}
  let notificationWillShowInForegroundBlock: OSNotificationWillShowInForegroundBlock = { notification, completion in
    print("Received Notification: ", notification.notificationId ?? "no id")
    print("launchURL: ", notification.launchURL ?? "no launch url")
    print("content_available = \(notification.contentAvailable)")

    if notification.notificationId == "example_silent_notif" {
      // Complete with null means don't show a notification  
      completion(nil)
    } else {
      // Complete with a notification means it will show
      completion(notification)
    }
  }
  OneSignal.setNotificationWillShowInForegroundHandler(notificationWillShowInForegroundBlock)
  ```

  ```objectivec objectivec theme={null}
  id notificationWillShowInForegroundBlock = ^(OSNotification *notification, OSNotificationDisplayResponse completion) {
          NSLog(@"Received Notification - %@", notification.notificationId);
          if ([notification.notificationId isEqualToString:@"silent_notif"]) {
              completion(nil);
          } else {
              completion(notification);
          }
      };

  [OneSignal setNotificationWillShowInForegroundHandler:notificationWillShowInForegroundBlock];
  ```

  ```javascript React Native theme={null}
  OneSignal.setNotificationWillShowInForegroundHandler(notificationReceivedEvent => {
    console.log("OneSignal: notification will show in foreground:", notificationReceivedEvent);
    let notification = notificationReceivedEvent.getNotification();
    console.log("notification: ", notification);
    const data = notification.additionalData
    console.log("additionalData: ", data);
    //Silence notification by calling complete() with no argument
    notificationReceivedEvent.complete(notification);
  });
  ```

  ```javascript Flutter theme={null}
  OneSignal.shared.setNotificationWillShowInForegroundHandler((OSNotificationReceivedEvent event) {
    // Display Notification, send null to not display, send notification to display           
    event.complete(event.notification);      
  });
  ```

  ```javascript Cordova/Ionic theme={null}
  window.plugins.OneSignal.setNotificationWillShowInForegroundHandler(function(notificationReceivedEvent) {
    notificationReceivedEvent.complete(notificationReceivedEvent.getNotification());
  });
  ```

  ```text Unity(C#) theme={null}
  OneSignal.Default.NotificationWillShow += onNotificationWillShow;

  Notification onNotificationWillShow(Notification notification) {
      if (someCheck)
          return null; // don't show the notificaiton

      // COMING SOON - make modifications to the notification before showing
      
      return notification; // show the notification
  }
  ```
</CodeGroup>

### `OSNotificationReceivedEvent` methods:

| Type                                                  | Field                                          | Description                                                                                                                                                                                                                                                                                                                                  |
| ----------------------------------------------------- | ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `void` (Android)`OSNotificationDisplayResponse` (iOS) | `complete()``completion()` (iOS Native)        | **Required:** Method controlling notification completion from the handler. If this is not called at the end of the `notificationWillShowInForeground` implementation, a runnable will fire after a 25 second timer and complete automatically. **Parameter:** - Display: pass the OSNotification object - Omit: pass null to omit displaying |
| `OSNotification`                                      | `getNotification()``notification` (iOS Native) | *Method* The notification the device received. See [OSNotification](#osnotification-class) for more details.                                                                                                                                                                                                                                 |

# Notification Opened Event

## `setNotificationOpenedHandler` Method

This method takes a `OSNotificationOpenedHandler` callback that itself accepts a parameter `result` of type `OSNotificationOpenedResult`.

| Platform | Parameter                     | Type     |
| -------- | ----------------------------- | -------- |
| Android  | `OSNotificationOpenedHandler` | Callback |
| iOS      | `OSNotificationOpenedBlock`   | Block    |

<CodeGroup>
  ```java java theme={null}
  OneSignal.setNotificationOpenedHandler(
     new OneSignal.OSNotificationOpenedHandler() {
       @Override
       public void notificationOpened(OSNotificationOpenedResult result) {
         String actionId = result.getAction().getActionId();
         String type = result.getAction().getType(); // "ActionTaken" | "Opened"
    
         String title = result.getNotification().getTitle();
       }
  });
  ```

  ```swift Swift theme={null}
  let notificationOpenedBlock: OSNotificationOpenedBlock = { result in
      // This block gets called when the user reacts to a notification received
      let notification: OSNotification = result.notification
      print("Message: ", notification.body ?? "empty body")
      print("badge number: ", notification.badge)
      print("notification sound: ", notification.sound ?? "No sound")
              
      if let additionalData = notification.additionalData {
          print("additionalData: ", additionalData)
          if let actionSelected = notification.actionButtons {
              print("actionSelected: ", actionSelected)
          }
          if let actionID = result.action.actionId {
              //handle the action
          }
      }
  }

  OneSignal.setNotificationOpenedHandler(notificationOpenedBlock)
  ```

  ```objectivec objectivec theme={null}
  id notificationOpenedBlock = ^(OSNotificationOpenedResult *result) {
    OSNotification* notification = result.notification;
    if (notification.additionalData) {
      if (result.action.actionId) {
        fullMessage = [fullMessage stringByAppendingString:[NSString stringWithFormat:@"\nPressed ButtonId:%@", result.action.actionId]];
      }
    }
    
  [OneSignal setNotificationOpenedHandler:notificationOpenedBlock];
  ```

  ```javascript React Native theme={null}
  OneSignal.setNotificationOpenedHandler(openedEvent => {
    console.log("OneSignal: notification opened:", openedEvent);
    const { action, notification } = openedEvent;
  });
  ```

  ```javascript Flutter theme={null}
  OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
      print('"OneSignal: notification opened: ${result}');
  });
  ```

  ```javascript Cordova/Ionic theme={null}
  var notificationOpenedCallback = function(jsonData) {
    var notificationData = JSON.stringify(jsonData)
    console.log('notificationOpenedCallback: ' + notificationData);
  };

  window.plugins.OneSignal.setNotificationOpenedHandler(notificationOpenedCallback);
  ```

  ```text Unity(C#) theme={null}
  OneSignal.Default.NotificationOpened += onNotificationOpened;

  void onNotificationOpened(NotificationOpenedResult result) {
      var notif = result.notification;
      var action = result.action;
  }
  ```
</CodeGroup>

**`OSNotificationOpenResult` fields:**

| Type                                                                         | Method/Property                                   | Description                                                                                                                                                                       |
| ---------------------------------------------------------------------------- | ------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`OSNotification`](#osnotification-payload#osnotification-class)             | `getNotification()` (Android)`notification` (iOS) | The notification the user received. See [`OSNotification`](#osnotification-payload#osnotification-class) for the full list of properties.                                         |
| [`OSNotificationAction`](#osnotification-payload#osnotificationaction-class) | `getAction()` (Android)`action` (iOS)             | The action the user took on the notification. String - **`getActionId()`** Enum - **`getType()`** [("Opened", "ActionTaken")](#osnotification-payload#osnotificationaction-class) |

# `OSNotification` Class

The `OSNotification` class is composed of all **getters**. The class combines the original `OSNotification` with data previously on the `OSNotificationPayload` class into a single large `OSNotification` class.

More details in [OSNotification Payload](/docs/en/osnotification-payload).

# `OSNotificationAction` Class

The action the user took on the notification.

More details in [OSNotification Payload](/docs/en/osnotification-payload).

***

# Background Notification Received Event

## Android Background Notification Received Event

Requires native code. See [Android Notification Service Extension](/docs/en/service-extensions#android-notification-service-extension) for more details.

## iOS Background Notification Received Event

#### `application(_:didReceiveRemoteNotification:fetchCompletionHandler:)` method

Apple provides this method to indicate a notification was received when your app is running in the foreground or background. This method allows data to be fetched while the app is running in the background. See details and discussion for requirements in [Apple's Developer Documentation](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application).

If your app is force-quite, this method will not run and requires the [Service Extensions](/docs/en/service-extensions) for detection.

You must have background mode enabled and send the push with `content_available` in the [iOS Message Settings](/docs/en/push#ios-options) for method to be called while app is in background.

<CodeGroup>
  ```swift Swift theme={null}
  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
      print("iOS Native didReceiveRemoteNotification: ", userInfo.debugDescription)
      
      if let customOSPayload = userInfo["custom"] as? NSDictionary {
          if let additionalData = customOSPayload["a"] as? NSDictionary {
              print("additionalData: ", additionalData)
              if let foo = additionalData["foo"] {
                  print("foo: ", foo)
              }
          }
          if let notificationId = customOSPayload["i"] {
              print("notificationId: ", notificationId)
          }
          if let launchUrl = customOSPayload["u"] {
              print("launchUrl: ", launchUrl)
          }
      }
      if let aps = userInfo["aps"] as? NSDictionary {
          if let alert = aps["alert"] as? NSDictionary {
              if let messageBody = alert["body"] {
                  print("messageBody: ", messageBody)
              }
              if let messageTitle = alert["title"] {
                  print("messageTitle: ", messageTitle)
              }
          }
      }
      // This block gets called when the user reacts to a notification received
      let timeInterval = Int(NSDate().timeIntervalSince1970)
      OneSignal.sendTags(["last_push_received": timeInterval])
      
      print("badge number: ", UIApplication.shared.applicationIconBadgeNumber.description)
  }
  ```
</CodeGroup>

***
