OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Discussions

SDK Notification Event Handlers

Handling Notification Events within OneSignal

The Notification Events on this page require the Major Release Versions of the OneSignal SDK.

Notification EventsDetails
Foreground Notification Received EventOneSignal 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 EventOneSignal SDK setNotificationOpenedHandler method runs upon opening the app after a notification is clicked.
Background Notification Received EventNative 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 EventiOS - 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 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 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.

Note: this runs after the Notification Service Extension which can be used to modify the notification before showing it.

PlatformParameterType
AndroidOSNotificationWillShowInForegroundHandlerCallback
iOSOSNotificationWillShowInForegroundBlockBlock
OneSiganl.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);
    }
  }
});
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)
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];
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);
});
OneSignal.shared.setNotificationWillShowInForegroundHandler((OSNotificationReceivedEvent event) {
  // Display Notification, send null to not display, send notification to display           
  event.complete(event.notification);      
});
window.plugins.OneSignal.handleNotificationWillShowInForeground(function(notificationReceivedEvent) {
  notificationReceivedEvent.complete(notificationReceivedEvent.notification);
});

OSNotificationReceivedEvent methods:

TypeFieldDescription
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
OSNotificationgetNotification()
notification (iOS Native)
Method
The notification the device received.

See OSNotification for more details.

Notification Opened Event

setNotificationOpenedHandler Method

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

PlatformParameterType
AndroidOSNotificationOpenedHandlerCallback
iOSOSNotificationOpenedBlockBlock
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();
     }
});
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)
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];
OneSignal.setNotificationOpenedHandler(openedEvent => {
  console.log("OneSignal: notification opened:", openedEvent);
  const { action, notification } = openedEvent;
});
OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
    print('"OneSignal: notification opened: ${result}');
});
var notificationOpenedCallback = function(jsonData) {
  var notificationData = JSON.stringify(jsonData)
  console.log('notificationOpenedCallback: ' + notificationData);
};

window.plugins.OneSignal.setNotificationOpenedHandler(notificationOpenedCallback);

OSNotificationOpenResult fields:

TypeMethod/PropertyDescription
OSNotificationgetNotification() (Android)
notification (iOS)
The notification the user received.
See OSNotification for the full list of properties.
OSNotificationActiongetAction() (Android)
action (iOS)
The action the user took on the notification.

String - getActionId()
Enum - getType() ("Opened", "ActionTaken")

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.

TypeMethod/PropertyDescription
JSONObject
NSDictionary
getAdditionalData (Android)
additionalData (iOS)
Gets custom additional data that was sent with the notification. Set on the dashboard under Options > Additional Data or with the data field on the REST API.
intgetAndroidNotificationId (Android)Gets the unique Android Native API identifier.
String
NSString
getNotificationId (Android)
notificationId (iOS)
Gets the OneSignal notification UUID.
String
NSString
getBody (Android)
body (iOS)
Gets the body text of the notification.
NSStringsubtitle (iOS)Message Subtitle, iOS only.
String
NSString
getTitle (Android)
title (iOS)
Gets the title text of the notification.
String
NSString
getLaunchURL (Android)
launchURL (iOS)
Gets the URL opened when opening the notification.
StringgetLargeIcon (Android)Gets the large icon set on the notification.
String
NSDictionary
getBigPicture (Android)
attachments (iOS)
Gets the big picture image set on the notification.

iOS 10+ only. Attachments sent as part of the rich notification
StringgetSmallIcon (Android)Gets the small icon resource name set on the notification.
StringgetSmallIconAccentColor (Android)Gets the accent color shown around small notification icon on Android 5+ devices. ARGB format.
BackgroundImageLayoutgetBackgroundImageLayout (Android)If a background image was set, this object will be available.

The following methods on this object return strings:
- getBodyTextColor()
- getImage()
- getTitleTextColor()
StringgetLedColor (Android)Get LED string. Devices that have a notification LED will blink in this color. ARGB format.
StringgetCollapseId (Android)Gets the collapse id for the notfication.
List<ActionButton>
NSArray
getActionButtons (Android)
actionButtons (iOS)
The list of action buttons on the notification.

The following methods on this object return strings:
- getIcon()
- getId()
- getText()
intgetPriority (Android)The priority of the notification. Values range from -2 to 2 (see Android's NotificationCompat reference for more info.
StringgetFromProjectNumber (Android)Gets the Google project number the notification was sent under.
List<OSNotification>getGroupedNotifications (Android)Gets the notification payloads a summary notification was created from.
StringgetGroupKey (Android)Notifications with this same key will be grouped together as a single summary notification.
StringgetGroupMessage (Android)Gets the summary text displayed in the summary notification.
intgetLockScreenVisibility (Android)Privacy setting for how the notification should be shown on the lockscreen of Android 5+ devices.

1 (Default) - Public (fully visible)
0 - Private (Contents are hidden)
-1 - Secret (not shown).
StringgetSound (Android)Gets the sound resource played when the notification is shown. Read more here
String, NSStringgetTemplateId (Android)
templateId (iOS)
Unique Template Identifier from Templates.
String, NSStringgetTemplateName (Android)Name of Template from Templates.
OSMutableNotificationmutableCopy (Android)Extends OSNotification

Methods
- setAndroidNotificationId(int id)
- setExtender(Extender extender)
ExtendergetNotificationExtender (Android)
String
NSDictionary
getRawPayload (Android)
rawPayload (iOS)
Gets raw JSON payload string received from OneSignal.

Holds the raw APS payload received.
NSStringcategory (iOS)iOS Notification category key previously registered to display with.
NSStringthreadId (iOS)iOS 10+ only. Groups notifications into threads
BOOLcontentAvailable (iOS)True when the key content-available is set to 1 in the APNS payload. Used to wake your app when the payload is received.

See Apple's documenation for more details.
BOOLmutableContent (iOS)True when the key mutable-content is set to 1 in the APNS payload.

See Apple's documenation for more details.
NSIntegerbadge (iOS)The badge number assigned to the application icon.
NSIntegerbadgeIncrement (iOS)The amount to increment the badge icon number.
MethodparseWithApns (iOS)Parses an APS push payload into a OSNotificationPayload object. Useful to call from your NotificationServiceExtension when the didReceiveNotificationRequest:withContentHandler: method fires.

OSNotificationAction Class

The action the user took on the notification.

TypeMethodDescription
String
NSString
getActionId() (Android)
actionID (iOS)
Notification button identifier
ActionTypegetType() (Android)
OSNotificationActionType (iOS)
The action type.

Enum:
0) Opened - notification was clicked
1) ActionTaken - button was clicked

Background Notification Received Event

Android Background Notification Received Event

Requires native code. See 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.

If your app is force-quite, this method will not run and requires the Service Extensions for detection.

Must have background mode enabled and send the push with content_available in the iOS Message Settings for method to be called while app is in background.

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)
}

Updated 19 days ago


SDK Notification Event Handlers


Handling Notification Events within OneSignal

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.