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 Reference

Comprehensive reference of OneSignal's SDK methods

SDK Guides


Debugging

setLogLevel Method

Enable logging to help debug if you run into an issue setting up OneSignal. This selector is static, so you can call it before OneSignal init.

Parameters

Type

Description

logLevel

LOG_LEVEL

Sets the logging level to print to the Android LogCat log or Xcode log.

visualLevel

LOG_LEVEL

Sets the logging level to show as alert dialogs.

//The following options are available with increasingly more information:
//NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
//The following options are available with increasingly more information: 
//.LL_NONE, .LL_FATAL, .LL_ERROR, .LL_WARN, .LL_INFO, .LL_DEBUG, .LL_VERBOSE.
OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
////The following options are available with increasingly more information: 
//ONE_S_LL_NONE, ONE_S_LL_FATAL, ONE_S_LL_ERROR, ONE_S_LL_WARN, ONE_S_LL_INFO, ONE_S_LL_DEBUG, ONE_S_LL_VERBOSE.
[OneSignal setLogLevel:ONE_S_LL_VERBOSE visualLevel:ONE_S_LL_NONE];
//The following options are available with increasingly more information:
//NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
//The following options are available with increasingly more information: 
//0 = NONE, 1 = FATAL, 2 = ERROR, 3 = WARN, 4 = INFO, 5 = DEBUG, 6 = VERBOSE
OneSignal.setLogLevel(6, 0);
//The following options are available with increasingly more information: 
//0 = NONE, 1 = FATAL, 2 = ERROR, 3 = WARN, 4 = INFO, 5 = DEBUG, 6 = VERBOSE
window.plugins.OneSignal.setLogLevel({logLevel: 6, visualLevel: 0});
//The following options are available with increasingly more information:
//none, fatal, error, warn, info, debug, verbose
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);
//The following options are available with increasingly more information:
//NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
// Needs: using Com.OneSignal.Abstractions;
OneSignal.Current.SetLogLevel(LOG_LEVEL.VERBOSE, LOG_LEVEL.NONE);
-- The following options are available with increasingly more information:
--0 = NONE, 1 = FATAL, 2 = ERROR, 3 = WARN, 4 = INFO, 5 = DEBUG, 6 = VERBOSE
OneSignal.SetLogLevel(6, 0)
//See this guide: https://documentation.onesignal.com/docs/troubleshooting-web-push#section-debugging-using-browser-developer-tools

Initialization Settings

Jump to your SDK specific docs for more details on initialization setup.

App In-Focus Notification Display

Setting to control how OneSignal notifications will be shown when one is received while your app is in focus.

Recommendation: Set to None or Notification when releasing to production.

Parameter

Details

InAppAlert

Default: Native alert dialog display (Note: this is not an In-App Message).

Notification

Native notification display while user has app in focus

None

Notification will not be displayed while app is in focus, but can be handled within the Notification Received Event Handler

OneSignal.setInFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification
OneSignal.inFocusDisplayType = OSNotificationDisplayTypeNotification;
OneSignal.inFocusDisplayType = OneSignal.OSInFocusDisplayOption.Notification;
// 0 = None, 1 = InAppAlert, 2 = Notification
OneSignal.inFocusDisplaying(2);
window.plugins.OneSignal
  .startInit("YOUR_APPID")
 .inFocusDisplaying(window.plugins.OneSignal.OSInFocusDisplayOption.Notification)
  .endInit();
OneSignal.shared.setInFocusDisplayType(OSNotificationDisplayType.notification);
OneSignal.Current.StartInit("YOUR_ONESIGNAL_APP_ID")
   .InFocusDisplaying(OSInFocusDisplayOption.Notification)
   .EndInit();
--More details: https://documentation.onesignal.com/docs/corona-sdk#section--kossettingskeyinfocusdisplayoption-
//Currently notifications will show while on site

iOS Push Prompting

iOS Apps have a native prompt that users click "Allow" to subscribe to push. You can use the below methods to trigger that prompt in your app. However, it is recommended to prompt users with a soft-prompt first. See OneSignal's In-App Messages with iOS Push Opt-In Prompt Guide.

// Call when you want to prompt the user to accept push notifications. 
// Only call once and only if you set kOSSettingsKeyAutoPrompt in AppDelegate to false.
OneSignal.promptForPushNotifications(userResponse: { accepted in
   print("User accepted notifications: \(accepted)")
})
[OneSignal promptForPushNotificationsWithUserResponse:^(BOOL accepted) {
  NSLog(@"Accepted Notifications?: %d", accepted);
}];
OneSignal.PromptForPushNotificationsWithUserResponse(OneSignal_promptForPushNotificationsResponse);

private void OneSignal_promptForPushNotificationsResponse(bool accepted) {
  Debug.Log("OneSignal_promptForPushNotificationsResponse: " + accepted);
}
// Calling registerForPushNotifications
OneSignal.promptForPushNotificationsWithUserResponse(myCallback);

function myCallback(permission){
    // do something with permission value
}
window.plugins.OneSignal.promptForPushNotificationsWithUserResponse(function(accepted) {
  console.log("User accepted notifications: " + accepted);
});
await OneSignal.shared.promptUserForPushNotificationPermission(fallbackToSettings: true);
OneSignal.Current.RegisterForPushNotifications();
OneSignal.RegisterForNotifications()

OneSignal Notification Events

Notification Received Handler

Called when the app receives a notification.

  • Android Native SDK calls this method when the app receives a notification while app is in focus or in the background.
  • iOS Native SDK calls this method when the app receives a notification while in focus only. If you need this to be called when your app is in the background, set content_available to true when you create your notification. The "force-quit" state (for example, if the app was swiped away) is not currently supported.
  • Non-native SDKs call this method when the app receives a notification while in focus only. To handle the notification while the device is not in focus, you must use the Service Extensions.

Jump to your SDK specific docs for more details on setup.

Parameter

Type

Description

notification

OSNotification

Contains both the user's response and properties of the notification.

class ExampleNotificationReceivedHandler implements OneSignal.NotificationReceivedHandler {
  @Override
  public void notificationReceived(OSNotification notification) {
    JSONObject data = notification.payload.additionalData;
    String customKey;

    if (data != null) {
      customKey = data.optString("customkey", null);
      if (customKey != null)
        Log.i("OneSignalExample", "customkey set with value: " + customKey);
    }
  }
}
let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in
    print("Received Notification - \(notification.payload.notificationID) - \(notification.payload.title)")
}
^(OSNotification *notification) {
    NSLog(@"Received Notification - %@ - %@", notification.payload.notificationID, notification.payload.title);
}
OneSignal.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba")
  .HandleNotificationReceived(HandleNotificationReceived)
  .EndInit();

// Called when your app is in focus and a notificaiton is recieved.
// The name of the method can be anything as long as the signature matches.
// Method must be static or this object should be marked as DontDestroyOnLoad
private static void HandleNotificationReceived(OSNotification notification) {
  OSNotificationPayload payload = notification.payload;
  string message = payload.body;

  print("GameControllerExample:HandleNotificationReceived: " + message);
  print("displayType: " + notification.displayType);
  extraMessage = "Notification received with text: " + message;
}
componentWillMount() {
    OneSignal.addEventListener('received', this.onReceived);
    OneSignal.addEventListener('opened', this.onOpened);
}

onReceived(notification) {
    console.log("Notification received: ", notification);
}

onOpened(openResult) {
    console.log('Message: ', openResult.notification.payload.body);
    console.log('Data: ', openResult.notification.payload.additionalData);
    console.log('isActive: ', openResult.notification.isAppInFocus);
}
window.plugins.OneSignal
  .startInit("YOUR_APPID")
  .handleNotificationReceived(function(notificationData) {
    alert("Notification Received:\n" + JSON.stringify(notificationData));
    console.log('Notification Received: ' + JSON.stringify(notificationData));
  })
  .endInit();
OneSignal.shared.setNotificationReceivedHandler((OSNotification notification) {
  // a notification has been received
});
private static void HandleNotificationReceived(OSNotification notification) {
  OSNotificationPayload payload = notification.payload;
  string message = payload.body;

  print("GameControllerExample:HandleNotificationReceived: " + message);
  print("displayType: " + notification.displayType);
  extraMessage = "Notification received with text: " + message;
}
--Currently not available
OneSignal.push(function() {
  OneSignal.on('notificationDisplay', function(event) {
    console.warn('OneSignal notification displayed:', event);
  });
});

Notification Opened Handler

Called when the user opens or taps an action on a notification.

Web SDK see the addListenerForNotificationOpened method.

Parameter

Type

Description

result

OSNotificationOpenedResult

Contains both the user's response and properties of the notification.

class ExampleNotificationOpenedHandler implements OneSignal.NotificationOpenedHandler {
  // This fires when a notification is opened by tapping on it.
  @Override
  public void notificationOpened(OSNotificationOpenResult result) {
    OSNotificationAction.ActionType actionType = result.action.type;
    JSONObject data = result.notification.payload.additionalData;
    String customKey;
    
    Log.i("OSNotificationPayload", "result.notification.payload.toJSONObject().toString(): " + result.notification.payload.toJSONObject().toString());


    if (data != null) {
      customKey = data.optString("customkey", null);
      if (customKey != null)
        Log.i("OneSignalExample", "customkey set with value: " + customKey);
    }

    if (actionType == OSNotificationAction.ActionType.ActionTaken)
      Log.i("OneSignalExample", "Button pressed with id: " + result.action.actionID);

    // The following can be used to open an Activity of your choice.
    // Replace - getApplicationContext() - with any Android Context.
    // Intent intent = new Intent(getApplicationContext(), YourActivity.class);
    // intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
    // startActivity(intent);

     // Add the following to your AndroidManifest.xml to prevent the launching of your main Activity
     //   if you are calling startActivity above.
     /* 
        <application ...>
          <meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
        </application>
     */
  }
}
let notificationOpenedBlock: OSHandleNotificationActionBlock = { result in
   // This block gets called when the user reacts to a notification received
   let payload: OSNotificationPayload = result!.notification.payload

   var fullMessage = payload.body
   print("Message = \(fullMessage)")

   if payload.additionalData != nil {
     if payload.title != nil {
         let messageTitle = payload.title
            print("Message Title = \(messageTitle!)")
      }

      let additionalData = payload.additionalData
      if additionalData?["actionSelected"] != nil {
         fullMessage = fullMessage! + "\nPressed ButtonID: \(additionalData!["actionSelected"])"
      }
   }
}
^(OSNotificationOpenedResult *result) {
        
   // This block gets called when the user opens or taps an action on a notification
   OSNotificationPayload* payload = result.notification.payload;
        
   NSString* messageTitle = @"OneSignal Example";
   NSString* fullMessage = [payload.body copy];
        
   if (payload.additionalData) {
      if (payload.title)
         messageTitle = payload.title;
            
      NSDictionary* additionalData = payload.additionalData;
            
      if (additionalData[@"actionSelected"])
         fullMessage = [fullMessage stringByAppendingString:[NSString stringWithFormat:@"\nPressed ButtonId:%@", additionalData[@"actionSelected"]]];
   }
  
   UIAlertView* alertView = [[UIAlertView alloc]
                               initWithTitle:messageTitle
                                     message:fullMessage
                                    delegate:self
                           cancelButtonTitle:@"Close"
                          otherButtonTitles:nil, nil];
   [alertView show];
}
OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
OneSignal.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba")
  .HandleNotificationOpened(HandleNotificationOpened)
  .EndInit();

// Called when a notification is opened.
// The name of the method can be anything as long as the signature matches.
// Method must be static or this object should be marked as DontDestroyOnLoad
private static void HandleNotificationOpened(OSNotificationOpenedResult result) {
  OSNotificationPayload payload = result.notification.payload;
  Dictionary<string, object> additionalData = payload.additionalData;
  string message = payload.body;
  string actionID = result.action.actionID;

  if (additionalData != null) {
    Debug.Log("result.notification.payload.additionalData = " + Json.Serialize(additionalData) as string);
    if (additionalData.ContainsKey("gotostore")) {
      // Take user to your store.
    }
  }
  if (actionID != null) {
    // actionSelected equals the id on the button the user pressed.
    // actionSelected will equal "__DEFAULT__" when the notification itself was tapped when buttons were present.
    Debug.Log("Pressed ButtonId: " + actionID);
  }
}
componentWillMount() {
    OneSignal.addEventListener('received', this.onReceived);
    OneSignal.addEventListener('opened', this.onOpened);
}

onReceived(notification) {
    console.log("Notification received: ", notification);
}

onOpened(openResult) {
    console.log('Message: ', openResult.notification.payload.body);
    console.log('Data: ', openResult.notification.payload.additionalData);
    console.log('isActive: ', openResult.notification.isAppInFocus);
}
window.plugins.OneSignal
  .startInit("YOUR_APPID")
  .handleNotificationOpened(function(openResult) {
    alert("Notification opened:\n" + JSON.stringify(openResult));
    console.log('Notification opened: ' + JSON.stringify(openResult));   
  })
  .endInit();
OneSignal.shared.setNotificationOpenedHandler((OSNotificationOpenedResult result) {
  // a notification has been opened
});
private static void HandleNotificationOpened(OSNotificationOpenedResult result) {
  OSNotificationPayload payload = result.notification.payload;
  Dictionary<string, object> additionalData = payload.additionalData;
  string message = payload.body;
  string actionID = result.action.actionID;

  print("GameControllerExample:HandleNotificationOpened: " + message);
  extraMessage = "Notification opened with text: " + message;

  if (additionalData != null) {
    if (additionalData.ContainsKey("discount")) {
      extraMessage = (string)additionalData["discount"];
      // Take user to your store.
    }
  }
  if (actionID != null) {
    // actionSelected equals the id on the button the user pressed.
    // actionSelected will equal "__DEFAULT__" when the notification itself was tapped when buttons were present.
    extraMessage = "Pressed ButtonId: " + actionID;
  }
}
--Currently not available
OneSignal.push(["addListenerForNotificationOpened", function(data) {
    console.log("Received NotificationOpened:");
    console.log(data);
}]);

OSNotificationOpenedResult Class

The information returned from a notification the user received.

Parameter

Type

Description

notification

OSNotification

Notification the user received.

action

OSNotificationAction

The action the user took on the notification.

OSNotification Class

The notification the user received.

Parameter

Type

Description

payload

OSNotificationPayload

Payload received from OneSignal.

displayType

iOS - OSNotificationDisplayType

Android & Other SDKs - displayType

How the notification was displayed to the user. See App In Focus Notification Displaying for more details.
Notification - 2 - Notification Displayed
InAppAlert - 1 - Default native alert shown.
None - 0 - No notification displayed

shown

Boolean

True when the user was able to see the notification. False when app is in focus and in-app alerts are disabled, or the remote notification is silent.

silentNotification - iOS Native SDK Only

Boolean

True when the received notification is silent. Silent means there is no alert, sound, or badge payload in the APS dictionary. Requires remote-notification within UIBackgroundModes array of the Info.plist

isAppInFocus - Not available in iOS Native SDK

Boolean

Was app in focus.

androidNotificationId - Not available in iOS Native SDK

Integer

Android Notification assigned to the notification. Can be used to cancel or replace the notification.

groupedNotifications - Not available in iOS Native SDK

List

Notification is a summary notification for a group this will contain all notification payloads it was created from.

OSNotificationAction Class

The action the user took on the notification.

Parameter

Type

Description

type

OSNotificationActionType

Was the notification opened normally (Opened) or was a button pressed on the notification (ActionTaken).

actionID

String

The ID associated with the button tapped. NULL when the actionType is NotificationTapped or InAppAlertClosed.

OSNotificationPayload Class

Contents and settings of the notification the user received.

Parameter

Type

Description

notificationID

String, NSString

OneSignal notification UUID.

title

String, NSString

Title text of the notification.

body

String, NSString

Body text of the notification.

subtitle

NSString

iOS subtitle text of the notification.

additionalData

JSONObject, NSDictionary

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.

contents_available

Boolean

iOS - Provided key with a value of 1 to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed application:didReceiveRemoteNotification:fetchCompletionHandler: is called.

smallIcon

String

Android small icon resource name set on the notification.

largeIcon

String

Android large icon set on the notification.

attachments

NSDictionary

iOS attachments sent as part of the rich notification.

bigPicture

String

Android big picture image set on the notification.

smallIconAccentColor

String

Accent color shown around small notification icon on Android 5+ devices. ARGB format.

launchUrl

String, NSString

URL to open when opening the notification.

badge

NSInteger

iOS badge number assigned to the application icon.

sound

String, NSString

Sound resource parameter to play when the notification is shown.

iOS default set to UILocalNotificationDefaultSoundName.

Read more about setting custom sound here

ledColor

String

Devices that have a notification LED will blink in this color. ARGB format.

lockScreenVisibility

int

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

groupKey

String

Notifications with this same key will be grouped together as a single summary notification.

groupMessage

string

Summary text displayed in the summary notification.

actionButtons

List<ActionButton>, NSArray

List of action buttons on the notification.

For more details, see how to handle action buttons.

fromProjectNumber

String

The Google project number the notification was sent under.

backgroundImageLayout

BackgroundImageLayout

Android background image was set this object will be available. For more details see Android Background Images

rawPayload

String, NSDictionary

Raw JSON payload string received from OneSignal.

parseWithApns

iOS Method

Parses an APS push payload into a OSNotificationPayload object. Useful to call from your NotificationServiceExtension when the didReceiveNotificationRequest:withContentHandler: method fires.

//result.notification.payload.toJSONObject().toString(): 
{ 
   "notificationID":"1fe89041-c33b-4bd6-87ad-fdf51157664a",
   "title":"Notification Title",
   "body":"Message of the notification",
   "additionalData":{ 
      "additional_data_key_1":"data_value_1",
      "data_key_2":"data_value_2"
   },
   "smallIcon":"small_icon_resource_name",
   "largeIcon":"https:\/\/img.onesignal.com\/n\/267522bc-e992-48d9-ad13-17d8f3336ae5.png",
   "bigPicture":"https:\/\/img.onesignal.com\/n\/65c5cba1-1bbd-49c4-9b26-ed7036a081f4.jpg",
   "smallIconAccentColor":"FF900FF",
   "launchURL":"https:\/\/onesignal.com\/launch-url",
   "lockScreenVisibility":1,
   "groupKey":"Group_key_23",
   "groupMessage":"Group_message",
   "actionButtons":[ 
      { 
         "id":"action_id",
         "text":"Shown_Text",
         "icon":"Icon_url"
      },
      { 
         "id":"action_id_2",
         "text":"Shown_text_2",
         "icon":"icon_url_2"
      }
   ],
   "fromProjectNumber":"388536902528",
   "collapseId":"collapse_id_1",
   "priority":6,
   "rawPayload":"{\"google.delivered_priority\":\"high\",\"google.sent_time\":1568060314614,\"google.ttl\":280000,\"google.original_priority\":\"high\",\"custom\":\"{\\\"a\\\":{\\\"additional_data_key_1\\\":\\\"data_value_1\\\",\\\"data_key_2\\\":\\\"data_value_2\\\",\\\"actionButtons\\\":[{\\\"id\\\":\\\"action_id\\\",\\\"text\\\":\\\"Shown_Text\\\",\\\"icon\\\":\\\"Icon_url\\\"},{\\\"id\\\":\\\"action_id_2\\\",\\\"text\\\":\\\"Shown_text_2\\\",\\\"icon\\\":\\\"icon_url_2\\\"}],\\\"actionSelected\\\":\\\"__DEFAULT__\\\"},\\\"u\\\":\\\"https:\\\\\\\/\\\\\\\/onesignal.com\\\\\\\/launch-url\\\",\\\"i\\\":\\\"1fe89041-c33b-4bd6-87ad-fdf51157664a\\\"}\",\"oth_chnl\":\"\",\"bgn\":\"1\",\"grp\":\"Group_key_23\",\"pri\":\"6\",\"vis\":\"1\",\"bgac\":\"FF900FF\",\"chnl\":\"{\\\"dscr\\\":\\\"test\\\",\\\"grp_nm\\\":\\\"test\\\",\\\"grp_id\\\":\\\"OS_1249f7c6-cb84-4685-8ba3-1a99b690ccdb\\\",\\\"id\\\":\\\"OS_fb1d04a7-dc4d-4d77-8b0a-8fb48ea2460b\\\",\\\"nm\\\":\\\"High Importance, default sound and vibration\\\"}\",\"from\":\"388536902528\",\"alert\":\"Message of the notification\",\"bicon\":\"https:\\\/\\\/img.onesignal.com\\\/n\\\/65c5cba1-1bbd-49c4-9b26-ed7036a081f4.jpg\",\"licon\":\"https:\\\/\\\/img.onesignal.com\\\/n\\\/267522bc-e992-48d9-ad13-17d8f3336ae5.png\",\"sicon\":\"small_icon_resource_name\",\"title\":\"Notification Title\",\"grp_msg\":\"Group_message\",\"google.message_id\":\"0:1568060314683605%616610dd87cd175f\",\"collapse_key\":\"collapse_id_1\",\"notificationId\":2143835591}"
}

User Status

Methods to get the OneSignal Player ID, subscription status, prompt status and push token.

Use getPermissionSubscriptionState to get the current immediate state. If called too early will be null or no available. - Use to load your UI to the correct state. Such as showing a toggle button to enable notifications.

Use addPermissionObserver or addSubscriptionObserver to react to changes. Use this to update your server when the user becomes subscribed or unsubscribed, and to get the OneSignal Player Id.

For example, if you need to store the OneSignal Player Id within your backend, you can make a REST API call directly from the observer's callback. The OneSignal observer fires only when there is a change (including not firing even if the app has been restarted). This helps ensure you are not making unnecessary network calls to your backend on each app restart if nothing changed.

getPermissionSubscriptionState Method

Get the current notification and permission state. Returns a OSPermissionSubscriptionState type, as described below.

OSPermissionSubscriptionState

Parameter

Type

Description

permissionStatus

OSPermissionState

Device Notification Permissions state

subscriptionStatus

OSSubscriptionState

Push Protocol and OneSignal subscription state

emailSubscriptionStatus

OSEmailState

Email Subscription State if set using setEmail method.

OSPermissionSubscriptionState status = OneSignal.getPermissionSubscriptionState();

status.getPermissionStatus().getEnabled();//Boolean: true - device subscribed in app settings, false - device unsubscribed in app settings
    
status.getSubscriptionStatus().getSubscribed();//Boolean: true - device can receive push from OS, false - device not subscribed from OneSignal or FCM 

status.getSubscriptionStatus().getUserSubscriptionSetting();//Boolean: true unless you have called setSubscription false

status.getSubscriptionStatus().getUserId();//String: the OS Player Id or null if device has not registered with OS Servers

status.getSubscriptionStatus().getPushToken();//The FCM Push Token or null if device has not registered with Google's servers

status.getEmailSubscriptionStatus().emailUserId();
status.getEmailSubscriptionStatus().emailAddress();
status.getEmailSubscriptionStatus().emailSubscribed();
let status: OSPermissionSubscriptionState = OneSignal.getPermissionSubscriptionState()

let hasPrompted = status.permissionStatus.hasPrompted
print("hasPrompted = \(hasPrompted)")
let userStatus = status.permissionStatus.status
print("userStatus = \(userStatus)")

let isSubscribed = status.subscriptionStatus.subscribed
print("isSubscribed = \(isSubscribed)")
let userSubscriptionSetting = status.subscriptionStatus.userSubscriptionSetting
print("userSubscriptionSetting = \(userSubscriptionSetting)")
let userID = status.subscriptionStatus.userId
print("userID = \(userID)")
let pushToken = status.subscriptionStatus.pushToken
print("pushToken = \(pushToken)")

let emailPlayerId = status.emailSubscriptionStatus.emailUserId
let emailAddress = status.emailSubscriptionStatus.emailAddress
let isEmailSubscribed = status.emailSubscriptionStatus.emailSubscribed
OSPermissionSubscriptionState* status = [OneSignal getPermissionSubscriptionState];
status.permissionStatus.hasPrompted;
status.permissionStatus.status;
    
status.subscriptionStatus.subscribed;
status.subscriptionStatus.userSubscriptionSetting;
status.subscriptionStatus.userId;
status.subscriptionStatus.pushToken;

status.emailSubscriptionStatus.emailUserId;
status.emailSubscriptionStatus.emailAddress;
status.emailSubscriptionStatus.emailSubscribed;
var status = OneSignal.GetPermissionSubscriptionState();
status.permissionStatus.hasPrompted;
status.permissionStatus.status;

status.subscriptionStatus.subscribed;
status.subscriptionStatus.userSubscriptionSetting;
status.subscriptionStatus.userId;
status.subscriptionStatus.pushToken;

status.emailSubscriptionStatus.emailUserId;
status.emailSubscriptionStatus.emailAddress;
status.emailSubscriptionStatus.emailSubscribed;
// Check push notification and OneSignal subscription statuses
OneSignal.getPermissionSubscriptionState((status) => {
    console.log(status);
});
window.plugins.OneSignal.getPermissionSubscriptionState(function(status) {
  status.permissionStatus.hasPrompted; // Bool
  status.permissionStatus.status; // iOS only: Integer: 0 = Not Determined, 1 = Denied, 2 = Authorized
  status.permissionStatus.state; //Android only: Integer: 1 = Authorized, 2 = Denied

  status.subscriptionStatus.subscribed; // Bool
  status.subscriptionStatus.userSubscriptionSetting; // Bool
  status.subscriptionStatus.userId; // String: OneSignal Player ID
  status.subscriptionStatus.pushToken; // String: Device Identifier from FCM/APNs

  status.emailSubscriptionStatus.emailUserId;
  status.emailSubscriptionStatus.emailAddress;
  status.emailSubscriptionStatus.emailSubscribed;
});
var status = await OneSignal.shared.getPermissionSubscriptionState();

if (status.permissionStatus.hasPrompted)
  // we know that the user was prompted for push permission
  
if (status.permissionStatus.status == OSNotificationPermission.notDetermined)
  // boolean telling you if the user enabled notifications

if (status.subscriptionStatus.subscribed)
  // boolean telling you if the user is subscribed with OneSignal's backend

// the user's ID with OneSignal
String onesignalUserId = status.subscriptionStatus.userId;

// the user's APNS or FCM/GCM push token
String token = status.subscriptionStatus.pushToken;

String emailPlayerId = status.emailSubscriptionStatus.emailUserId;
String emailAddress = status.emailSubscriptionStatus.emailAddress;
Bool isEmailSubscribed = status.emailSubscriptionStatus.emailSubscribed;
//More details: https://documentation.onesignal.com/docs/xamarin-sdk#section--idsavailablecallback-
private void IdsAvailable(string userID, string pushToken) {
    print("UserID:"  + userID);
    print("pushToken:" + pushToken);
}
--More details: https://documentation.onesignal.com/docs/corona-sdk#section--idsavailablecallback-
function IdsAvailable(userID, pushToken)
    print("PLAYER_ID:" .. userID)
    if (pushToken) then -- nil if user did not accept push notifications on iOS
        print("PUSH_TOKEN:" .. pushToken)
    end
end

OneSignal.IdsAvailableCallback(IdsAvailable)
//More details: https://documentation.onesignal.com/docs/web-push-sdk#section--getuserid-
OneSignal.push(function() {
  OneSignal.getUserId(function(userId) {
    console.log("OneSignal User ID:", userId);
    // (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316    
  });
});

addPermissionObserver Method

The onOSPermissionChanged method will be fired on the passed-in object when a notification permission setting changes.

This includes the following events:

  • Notification permission prompt shown (iOS)
  • The user accepting or declining the permission prompt (iOS)
  • Enabling or disabling notifications for your app in the App Settings and after returning to your app

Instance is given to your onOSPermissionChanged method, which provides what the value was ("from") and what the value is now ("to").

Any object implementing the OSPermissionObserver and/or the OSSubscriptionObserver protocols can be added as an observer. You can call removePermissionObserver to remove any existing listeners.

OneSignal uses a weak reference to the observer to prevent leaks.

public class MainActivity extends Activity implements OSPermissionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addPermissionObserver(this);
  }
  
  public void onOSPermissionChanged(OSPermissionStateChanges stateChanges) {
    if (stateChanges.getFrom().getEnabled() &&
        !stateChanges.getTo().getEnabled()) {
         new AlertDialog.Builder(this)
             .setMessage("Notifications Disabled!")
             .show();
      }
   
      Log.i("Debug", "onOSPermissionChanged: " + stateChanges);
  }
}

// Example Logcat entry - User disabling notifications then returning to your app.
// onOSPermissionChanged{"from":{"enabled":true},"to":{"enabled":false}}
// AppDelegate.swift
// Add OSPermissionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSPermissionObserver {

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      // Add your AppDelegate as an obsserver
      OneSignal.add(self as OSPermissionObserver)
   }

   // Add this new method
   func onOSPermissionChanged(_ stateChanges: OSPermissionStateChanges!) {
      // Example of detecting answering the permission prompt
      if stateChanges.from.status == OSNotificationPermission.notDetermined {
         if stateChanges.to.status == OSNotificationPermission.authorized {
            print("Thanks for accepting notifications!")
         } else if stateChanges.to.status == OSNotificationPermission.denied {
            print("Notifications not accepted. You can turn them on later under your iOS settings.")
         }
      }
      // prints out all properties
      print("PermissionStateChanges: \n\(stateChanges)")
   }

   // Output:
   /*
   Thanks for accepting notifications!
   PermissionStateChanges:
   Optional(<OSSubscriptionStateChanges:
   from: <OSPermissionState: hasPrompted: 0, status: NotDetermined>,
   to:   <OSPermissionState: hasPrompted: 1, status: Authorized>
   >
   */
}
// AppDelegate.h
// Add OSPermissionObserver after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSPermissionObserver>
@end

// AppDelegate.m
@implementation AppDelegate
  
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Add your AppDelegate as an obsserver
  [OneSignal addPermissionObserver:self];
}

// Add this new method
- (void)onOSPermissionChanged:(OSPermissionStateChanges*)stateChanges {
  
    // Example of detecting anwsering the permission prompt
    if (stateChanges.from.status == OSNotificationPermissionNotDetermined) {
      if (stateChanges.to.status == OSNotificationPermissionAuthorized)
         NSLog(@"Thanks for accepting notifications!");
      else if (stateChanges.to.status == OSNotificationPermissionDenied)
         NSLog(@"Notifications not accepted. You can turn them on later under your iOS settings.");
    }
    
   // prints out all properties 
   NSLog(@"PermissionStateChanges:\n%@", stateChanges);
}

// Output:
/*
Thanks for accepting notifications!
PermissionStateChanges:
<OSSubscriptionStateChanges:
from: <OSPermissionState: hasPrompted: 1, status: NotDetermined>,
to:   <OSPermissionState: hasPrompted: 1, status: Authorized>
>
*/

@end
OneSignal.permissionObserver += OneSignal_permissionObserver;

private void OneSignal_permissionObserver(OSPermissionStateChanges stateChanges) {
       // Example of detecting anwsering the permission prompt
    if (stateChanges.from.status == OSNotificationPermission.NotDetermined) {
      if (stateChanges.to.status == OSNotificationPermission.Authorized)
         Debug.Log("Thanks for accepting notifications!");
      else if (stateChanges.to.status == OSNotificationPermission.Denied)
         Debug.Log("Notifications not accepted. You can turn them on later under your device settings.");
    }
   
    Debug.Log("stateChanges.to.status: " + stateChanges.to.status);
}
// Requesting permissions
OneSignal.checkPermissions((permissions) => {
    console.log(permissions);
});
window.plugins.OneSignal.addPermissionObserver(function(state) {
  console.log("Notification permission state changed: " + state.hasPrompted);
  console.log("Notification permission status: " + state.status);
});
OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {
    // will be called whenever the permission changes
  
  if (changes.to.status == OSNotificationPermission.authorized) {
    //tells you that the user has fully authorized push permissions
  }
});
//Currently not available, use the idsAvailableCallback and check if a pushtoken is provided to make sure the user is subscribed
--Currently not available, use the idsAvailableCallback and check if a pushtoken is provided to make sure the user is subscribed
OneSignal.push(function() {
  OneSignal.on('notificationPermissionChange', function(permissionChange) {
    var currentPermission = permissionChange.to;
    console.log('New permission state:', currentPermission);
  });
  
  // This event can be listened to via the on() or once() listener
});

Subscription Observer Method

Web SDK has more details in Subscription Change Event.

The onOSSubscriptionChanged method will be fired on the passed in object when a notification subscription property changes.

This includes the following events:

  • Getting a push token from Google or Apple
  • Getting a player / user id from OneSignal
  • OneSignal.setSubscription is called
  • User disables or enables notifications

Instance is given to your onOSSubscriptionChanged method which provides what the value was ("from") and what the value is now ("to").

Any object implementing the OSPermissionObserver and/or the OSSubscriptionObserver protocols can be added as an observer. You can call removePermissionObserver to remove any existing listeners.

OneSignal uses a weak reference to the observer to prevent leaks.

public class MainActivity extends Activity implements OSSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addSubscriptionObserver(this);
  }
  
  public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
    if (!stateChanges.getFrom().getSubscribed() &&
        stateChanges.getTo().getSubscribed()) {
         new AlertDialog.Builder(this)
             .setMessage("You've successfully subscribed to push notifications!")
             .show();
        // get player ID
        stateChanges.getTo().getUserId();
      }
   
      Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
  }
}

/*
Example Logcat entry - User disabling notifications then returning to your app.
onOSSubscriptionChanged:
{"from":{"pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":false},
 "to":  {"userId":"22712a53-9b5c-4eab-a828-f18f81167fef","pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":true}}
// AppDelegate.swift
// Add OSSubscriptionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSSubscriptionObserver {

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
      // Add your AppDelegate as an obsserver
      OneSignal.add(self as OSSubscriptionObserver)
   }

   // Add this new method
   func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) {
      if !stateChanges.from.subscribed && stateChanges.to.subscribed {
         print("Subscribed for OneSignal push notifications!")
         // get player ID
         stateChanges.to.userId
      }
      print("SubscriptionStateChange: \n\(stateChanges)")
   }

   // Output:
   /*
   Subscribed for OneSignal push notifications!
   PermissionStateChanges:
   Optional(<OSSubscriptionStateChanges:
   from: <OSSubscriptionState: userId: (null), pushToken: 0000000000000000000000000000000000000000000000000000000000000000 userSubscriptionSetting: 1, subscribed: 0>,
   to:   <OSSubscriptionState: userId: 11111111-222-333-444-555555555555, pushToken: 0000000000000000000000000000000000000000000000000000000000000000, userSubscriptionSetting: 1, subscribed: 1>
   >
   */
}
// AppDelegate.h
// Add OSSubscriptionObserver after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSSubscriptionObserver>
@end

// AppDelegate.m
@implementation AppDelegate
  
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Add your AppDelegate as an obsserver
  [OneSignal addSubscriptionObserver:self];
}

// Add this new method
- (void)onOSSubscriptionChanged:(OSSubscriptionStateChanges*)stateChanges {
  
    // Example of detecting subscribing to OneSignal
    if (!stateChanges.from.subscribed && stateChanges.to.subscribed) {
      NSLog(@"Subscribed for OneSignal push notifications!");
      // get player ID
      stateChanges.to.userId;
    }
    
   // prints out all properties
   NSLog(@"SubscriptionStateChanges:\n%@", stateChanges);
}

// Output:
/*
Subscribed for OneSignal push notifications!
PermissionStateChanges:
<OSSubscriptionStateChanges:
from: <OSSubscriptionState: userId: (null), pushToken: 0000000000000000000000000000000000000000000000000000000000000000 userSubscriptionSetting: 1, subscribed: 0>,
to:   <OSSubscriptionState: userId: 11111111-222-333-444-555555555555, pushToken: 0000000000000000000000000000000000000000000000000000000000000000, userSubscriptionSetting: 1, subscribed: 1>
>
*/

@end
//More details: https://documentation.onesignal.com/docs/unity-sdk#section-subscription-observer
OneSignal.subscriptionObserver += OneSignal_subscriptionObserver;

private void OneSignal_subscriptionObserver(OSSubscriptionStateChanges stateChanges) {
      Debug.Log("stateChanges: " + stateChanges);
      Debug.Log("stateChanges.to.userId: " + stateChanges.to.userId);
      Debug.Log("stateChanges.to.subscribed: " + stateChanges.to.subscribed);
   }
//Not available at this time, use getPermissionSubscriptionState
//More details: https://documentation.onesignal.com/docs/cordova-sdk#section--addsubscriptionobserver-
window.plugins.OneSignal.addSubscriptionObserver(function (state) {
  if (!state.from.subscribed && state.to.subscribed) {
    console.log("Subscribed for OneSignal push notifications!")
    // get player ID
    state.to.userId
  }
  console.log("Push Subscription state changed: " + JSON.stringify(state));
});
//More details: https://documentation.onesignal.com/docs/flutter-sdk#section--setsubscriptionobserver-
OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
  //will be called whenever the OS subscription changes
});
//Currently not available, use the idsAvailableCallback and check if a pushtoken is provided to make sure the user is subscribed: https://documentation.onesignal.com/docs/xamarin-sdk#section--idsavailablecallback-
--Currently not available, use the idsAvailableCallback and check if a pushtoken is provided to make sure the user is subscribed: https://documentation.onesignal.com/docs/corona-sdk#section--idsavailablecallback-
//More details: https://documentation.onesignal.com/docs/web-push-sdk#section-subscription-change
OneSignal.push(function() {
  // Occurs when the user's subscription changes to a new value.
  OneSignal.on('subscriptionChange', function (isSubscribed) {
    console.log("The user's subscription state is now:", isSubscribed);
  });
});

setSubscription Method

The user must first subscribe through the native prompt or app settings. It does not officially subscribe or unsubscribe them from the app settings, it unsubscribes them from receiving push from OneSignal.
You can only call this method with false to opt out users from receiving notifications through OneSignal. You can pass true later to opt users back into notifications.

OneSignal.setSubscription(false);
OneSignal.setSubscription(false)
[OneSignal setSubscription:false];
OneSignal.SetSubscription(false);
// Setting setSubscription
OneSignal.setSubscription(true);
window.plugins.OneSignal.setSubscription(false);
await OneSignal.shared.setSubscription(true);
OneSignal.SetSubscription(false);
OneSignal.SetSubscription(false)
OneSignal.setSubscription(false);

External User Ids

setExternalUserId Method

If your system assigns unique identifiers to users, it can be to have to also remember their OneSignal Player Id's as well. To make things easier, OneSignal now allows you to set an external_user_id for your users. Simply call this method, pass in your custom user Id (as a string), and from now on when you send a push notification, you can use include_external_user_ids instead of include_player_ids.

String externalUserId = "123456789"; // You will supply the external user id to the OneSignal SDK

// Setting External User Id with Callback Available in SDK Version 3.13.0+
OneSignal.setExternalUserId(externalUserId, new OneSignal.OSExternalUserIdUpdateCompletionHandler() {
  @Override
  public void onComplete(JSONObject results) {
    // The results will contain push and email success statuses
    OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Set external user id done with results: " + results.toString());

    // Push can be expected in almost every situation with a success status, but
    // as a pre-caution its good to verify it exists
    if (results.has("push") && results.getJSONObject("push").has("success")) {
      boolean isPushSuccess = results.getJSONObject("push").getBoolean("success");
      OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Set external user id for push status: " + isPushSuccess);
    }
    
    // Verify the email is set or check that the results have an email success status
    if (results.has("email") && results.getJSONObject("email").has("success")) {
      boolean isEmailSuccess = results.getJSONObject("email").getBoolean("success");
      OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Sets external user id for email status: " + isEmailSuccess);
    }
  }
});

//Available with SDK Version 3.12.7-
//OneSignal.setExternalUserId(myCustomUniqueUserId);
let externalUserId = "123456789" // You will supply the external user id to the OneSignal SDK

// Setting External User Id with Callback Available in SDK Version 2.13.1+
OneSignal.setExternalUserId(externalUserId, withCompletion: { results in
  // The results will contain push and email success statuses
  print("External user id update complete with results: ", results!.description)
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if let pushResults = results!["push"] {
    print("Set external user id push status: ", pushResults)
  }
  if let emailResults = results!["email"] {
      print("Set external user id email status: ", emailResults)
  }
})

//Available in SDK Version 2.13.0-
//OneSignal.setExternalUserId(myCustomUniqueUserId)
NSString* externalUserId = @"123456789"; // You will supply the external user id to the OneSignal SDK

// Setting External User Id with Callback Available in SDK Version 2.13.0+
[OneSignal setExternalUserId:externalUserId withCompletion:^(NSDictionary *results) {
  // The results will contain push and email success statuses
  NSLog(@"External user id update complete with results: %@", results.description);
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results["push"] && results["push"]["success"])
    NSLog(@"Set external user id push status: %@", results["push"]["success"]);
  // Verify the email is set or check that the results have an email success status
  if (results["email"] && results["email"]["success"])
    NSLog(@"Set external user id email status: %@", results["email"]["success"]);
}];

//Available in SDK Version 2.12.6-
//[OneSignal setExternalUserId:myCustomUniqueUserId];
// Setting External User Id with Callback
string externalId = "123456789"; // You will supply the external user id to the OneSignal SDK

// Setting External User Id with Callback Available in SDK Version 2.12.0+
OneSignal.Current.SetExternalUserId(externalId, OneSignalSetExternalUserId);

// Removing External User Id with Callback Available in SDK Version 2.12.0+
//OneSignal.Current.RemoveExternalUserId(OneSignalSetExternalUSerId);

//Callback available in SDK Version 2.12.0+
private static void OneSignalSetExternalUserId(Dictionary<string, object> results)
{
  // The results will contain push and email success statuses
  Debug.WriteLine("External user id updated with results: " + Json.Serialize(results));
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.ContainsKey("push"))
  {
    Dictionary<string, object> pushStatusDict = results["push"] as Dictionary<string, object>;
    if (pushStatusDict.ContainsKey("success"))
    {
      Debug.WriteLine("External user id updated for push with results: " + pushStatusDict["success"] as string);
    }
  }
  // Verify the email is set or check that the results have an email success status
  if (results.ContainsKey("email"))
  {
    Dictionary<string, object> emailStatusDict = results["email"] as Dictionary<string, object>;
    if (emailStatusDict.ContainsKey("success"))
    {
      Debug.WriteLine("External user id updated for email with results: " + emailStatusDict["success"] as string);
    }
  }
}

// Available with SDK 2.11.4-
//OneSignal.SetExternalUserId(myCustomUniqueUserId);
let externalUserId = '123456789'; // You will supply the external user id to the OneSignal SDK

// Setting External User Id with Callback Available in SDK Version 3.7.0+
OneSignal.setExternalUserId(externalUserId, (results) => {
  // The results will contain push and email success statuses
  console.log('Results of setting external user id');
  console.log(results);
  
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.push && results.push.success) {
    console.log('Results of setting external user id push status:');
    console.log(results.push.success);
  }
  
  // Verify the email is set or check that the results have an email success status
  if (results.email && results.email.success) {
    console.log('Results of setting external user id email status:');
    console.log(results.email.success);
  }
});

//Available in SDK Version 3.6.5-
//OneSignal.setExternalUserId(myCustomUniqueUserId);
let externalUserId = '123456789'; // You will supply the external user id to the OneSignal SDK

// Setting External User Id with Callback Available in SDK Version 2.9.0+
OneSignal.setExternalUserId(externalUserId, (results) => {
  // The results will contain push and email success statuses
  console.log('Results of setting external user id');
  console.log(results);
  
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.push && results.push.success) {
    console.log('Results of setting external user id push status:');
    console.log(results.push.success);
  }
  
  // Verify the email is set or check that the results have an email success status
  if (results.email && results.email.success) {
    console.log('Results of setting external user id email status:');
    console.log(results.email.success);
  }
});

//Available in SDK Version 2.8.4-
//OneSignal.setExternalUserId(myCustomUniqueUserId);
var myCustomUniqueUserId = "something from my backend server";

OneSignal.shared.setExternalUserId(myCustomUniqueUserId);
// Setting External User Id with Callback
string externalId = "123456789"; // You will supply the external user id to the OneSignal SDK

// Setting External User Id with Callback Available in SDK Version 3.8.0+
OneSignal.Current.SetExternalUserId(externalId, OneSignalSetExternalUserId);

// Removing External User Id with Callback Available in SDK Version 3.8.0+
//OneSignal.Current.RemoveExternalUserId(OneSignalSetExternalUSerId);

//Callback available in SDK Version 3.8.0+
private static void OneSignalSetExternalUserId(Dictionary<string, object> results)
{
  // The results will contain push and email success statuses
  Debug.WriteLine("External user id updated with results: " + Json.Serialize(results));
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.ContainsKey("push"))
  {
    Dictionary<string, object> pushStatusDict = results["push"] as Dictionary<string, object>;
    if (pushStatusDict.ContainsKey("success"))
    {
      Debug.WriteLine("External user id updated for push with results: " + pushStatusDict["success"] as string);
    }
  }
  // Verify the email is set or check that the results have an email success status
  if (results.ContainsKey("email"))
  {
    Dictionary<string, object> emailStatusDict = results["email"] as Dictionary<string, object>;
    if (emailStatusDict.ContainsKey("success"))
    {
      Debug.WriteLine("External user id updated for email with results: " + emailStatusDict["success"] as string);
    }
  }
}

// Available with SDK 3.7.3-
//OneSignal.Current.SetExternalUserId(myCustomUniqueUserId);
--Currently not available
let myCustomUniqueUserId = "something from my backend server";

OneSignal.push(function() {
  OneSignal.setExternalUserId(myCustomUniqueUserId);
});

removeExternalUserId Method

If your user logs out of your app, and you would like to disassociate their custom User ID from your system with their OneSignal User ID, you will want to call this method.

// Removing External User Id with Callback Available in SDK Version 3.13.0+
OneSignal.removeExternalUserId(new OneSignal.OSExternalUserIdUpdateCompletionHandler() {
  @Override
    public void onComplete(JSONObject results) {
    // The results will contain push and email success statuses
    OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Remove external user id done with results: " + results.toString());
    
    // Push can be expected in almost every situation with a success status, but
    // as a pre-caution its good to verify it exists
    if (results.has("push") && results.getJSONObject("push").has("success")) {
      boolean isPushSuccess = results.getJSONObject("push").getBoolean("success");
      OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Remove external user id for push status: " + isPushSuccess);
    }
    
    // Verify the email is set or check that the results have an email success status
    if (results.has("email") && results.getJSONObject("email").has("success")) {
      boolean isEmailSuccess = results.getJSONObject("email").getBoolean("success");
      OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Remove external user id for email status: " + isEmailSuccess);
    }
  }
});


//Available in SDK Version 3.12.7-
//OneSignal.removeExternalUserId();
// Removing External User Id with Callback Available in SDK Version 2.13.1+
OneSignal.removeExternalUserId({ results in
    // The results will contain push and email success statuses
    print("External user id update complete with results: ", results!.description)
    // Push can be expected in almost every situation with a success status, but
    // as a pre-caution its good to verify it exists
    if let pushResults = results!["push"] {
        print("Remove external user id push status: ", pushResults)
    }
    // Verify the email is set or check that the results have an email success status
    if let emailResults = results!["email"] {
        print("Remove external user id email status: ", emailResults)
    }
})

//Available in SDK Version 2.13.0-
//OneSignal.removeExternalUserId()
// Removing External User Id with Callback Available in SDK Version 2.13.0+
[OneSignal removeExternalUserId:^(NSDictionary *results) {
  // The results will contain push and email success statuses
  NSLog(@"External user id update complete with results: %@", results.description);
  
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results["push"] && results["push"]["success"])
    NSLog(@"Remove external user id push status: %@", results["push"]["success"]);
  
  // Verify the email is set or check that the results have an email success status
  if (results["email"] && results["email"]["success"])
    NSLog(@"Remove external user id email status: %@", results["email"]["success"]);
}];

//Available in SDK Version 2.12.6-
//[OneSignal removeExternalUserId];
// Removing External User Id with Callback Available in SDK Version 2.12.0+
OneSignal.Current.RemoveExternalUserId(OneSignalSetExternalUserId);

//See setExternalUserId method for callback Available in SDK Version 2.12.0+

// Available with SDK 2.11.4-
//OneSignal.RemoveExternalUserId();
// Remove External User Id with Callback Available in SDK Version 3.7.0+
OneSignal.removeExternalUserId((results) => {
  // The results will contain push and email success statuses
  console.log('Results of removing external user id');
  console.log(results);
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.push && results.push.success) {
    console.log('Results of removing external user id push status:');
    console.log(results.push.success);
  }
  
  // Verify the email is set or check that the results have an email success status
  if (results.email && results.email.success) {
    console.log('Results of removoing external user id email status:');
    console.log(results.email.success);
  }
});

//Available in SDK Version 3.6.5-
//OneSignal.removeExternalUserId()
// Remove External User Id with Callback Available in SDK Version 2.9.0+
window.plugins.OneSignal.removeExternalUserId((results) => {
  // The results will contain push and email success statuses
  console.log('Results of removing external user id');
  console.log(results);
  // Push can be expected in almost every situation with a success status, but
  // as a pre-caution its good to verify it exists
  if (results.push && results.push.success) {
    console.log('Results of removing external user id push status:');
    console.log(results.push.success);
  }
  
  // Verify the email is set or check that the results have an email success status
  if (results.email && results.email.success) {
    console.log('Results of removoing external user id email status:');
    console.log(results.email.success);
  }
});

//Available in SDK Version 2.8.4-
//window.plugins.OneSignal.removeExternalUserId();
//usually called after the user logs out of your app
OneSignal.shared.removeExternalUserId()
// Removing External User Id with Callback Available in SDK Version 3.8.0+
OneSignal.Current.RemoveExternalUserId(OneSignalSetExternalUserId);

//See setExternalUserId method for callback Available in SDK Version 3.8.0+

// Available with SDK 3.7.3-
//OneSignal.Current.RemoveExternalUserId()
--Currently not available
OneSignal.push(function() {
  OneSignal.removeExternalUserId();
});

Privacy

setRequiresUserPrivacyConsent Method

For GDPR users, your application should call this method before initialization of the SDK.

If you pass in true, your application will need to call provideConsent(true) before the OneSignal SDK gets fully initialized. Until this happens, you can continue to call methods (such as sendTags()), but nothing will happen.

OneSignal.setRequiresUserPrivacyConsent(true);
//to require the user's consent before the SDK initializes
OneSignal.setRequiresUserPrivacyConsent(true);

OneSignal.initWithLaunchOptions(launchOptions, appId: "YOUR_ONESIGNAL_APP_ID");
//to require the user's consent before the SDK initializes
[OneSignal setRequiresUserPrivacyConsent:true];

[OneSignal initWithLaunchOptions:launchOptions appId:@"YOUR_ONESIGNAL_APP_ID"];
void YourAppInitMethod() {
  // SetRequiresUserPrivacyConsent will prevent
  //   initialization until UserDidProvideConsent(true) is called
  OneSignal.StartInit("YOUR_APP_ID")
    .SetRequiresUserPrivacyConsent(true)
    .EndInit();
}
componentWillMount() {
  // Will delay initialization of the SDK until the user provides consent
  OneSignal.setRequiresUserPrivacyConsent(true);
  OneSignal.init("YOUR_ONESIGNAL_APPID");
}
//will delay initialization of the SDK until the user provides consent
window.plugins.OneSignal.setRequiresUserPrivacyConsent(true);
await OneSignal.shared.setRequiresUserPrivacyConsent(true);

await OneSignal.shared.init("b2f7f966-d8cc-11e4-bed1-df8f05be55ba");
//will delay initialization of the SDK
//make sure to call before init()
OneSignal.SetRequiresUserPrivacyConsent(true);
--Not available
//Add to the init call parameters: https://documentation.onesignal.com/docs/web-push-sdk#init
requiresUserPrivacyConsent: true,

Consent Granted

If your application is set to require the user's privacy consent, you can provide this consent using this method. Until you call provideUserConsent(true), the SDK will not fully initialize, and will not send any data to OneSignal.

public void onUserTappedProvidePrivacyConsent(View v) {
  //will initialize the OneSignal SDK and enable push notifications
  OneSignal.provideUserConsent(true);
}
@IBAction func userTappedProvideConsentButton(_ sender : UIButton) {
  //this will complete the initialization of the SDK
    OneSignal.consentGranted(true); 
}
- (IBAction)setEmailButtonPressed:(UIButton *)sender {
  //this will complete the initialization of the SDK
  [OneSignal consentGranted:true];
}
void UserAcceptedConsent() {
   // Only needs to be called once,
   //   OneSignal will remember the last answer 
   OneSignal.UserDidProvideConsent(true);
}
function userTappedProvideConsentButton() {
  // Will initialize the SDK and register for push notifications
  OneSignal.provideUserConsent(true);
}
window.plugins.OneSignal.userProvidedPrivacyConsent((providedConsent) => {
  //if providedConsent == true, it means the SDK has been initialized and can be used
});
// the SDK will now initialize
await OneSignal.shared.consentGranted(true);
PrivacyConsentButton.TouchUpInside += delegate
{
  //the SDK will now be initialized
    OneSignal.UserDidProvidePrivacyConsent(true);
};
--Not available
function userTappedProvideConsentButton() {
  // Will initialize the SDK and register for push notifications
  OneSignal.push(function() {
    OneSignal.provideUserConsent(true);
  });
}

Location Data

setLocationShared Method

Disable or enable location collection (defaults to enabled if your app has location permission).

Note: This method must be called before OneSignal initWithLaunchOptions on iOS.

OneSignal.setLocationShared(false);
OneSignal.setLocationShared(false)
[OneSignal setLocationShared:false];
void UserAcceptedConsent() {
   // Only needs to be called once,
   //   OneSignal will remember the last answer 
   OneSignal.UserDidProvideConsent(true);
}
OneSignal.setLocationShared(false);
window.plugins.OneSignal.setLocationShared(false)
await OneSignal.shared.setLocationShared(true);
OneSignal.SetLocationShared(false);
--Currently not available
//Our Web SDK does not track location, you can setup the browser to track this and tag the user with the latitutde and longitude

promptLocation Method

Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. This lets you send notifications based on the device's location. See Location-Triggered Notifications for more details.

Make sure you add location permissions in your AndroidManifest.xml and/or info.plist.

// Make sure you add one of the following permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
//These are examples of how you may setup the app. See Apple's Guide on this: https://developer.apple.com/documentation/corelocation/requesting_authorization_for_location_services
// Example plist image: https://i.imgur.com/OZDQpyQ.png

<key>NSLocationUsageDescription</key>
  <string>Your message goes here</string>
<key>NSLocationWhenInUseUsageDescription</key>
    <string>Your message goes here</string>  
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>Your message goes here</string>
<key>NSLocationAlwaysUsageDescription</key>
    <string>Your message goes here</string>
<key>UIBackgroundModes</key>
    <array>
        <string>location</string>
        <string>remote-notification</string>
    </array>
OneSignal.promptLocation();
OneSignal.promptLocation()
[OneSignal promptLocation];
OneSignal.PromptLocation();
// Calling promptLocation
OneSignal.promptLocation();
window.plugins.OneSignal.promptLocation();
await OneSignal.shared.promptLocationPermission();
OneSignal.Current.PromptLocation();
--More details: https://documentation.onesignal.com/docs/corona-sdk#section--promptlocation-
OneSignal.PromptLocation();
//Our Web SDK does not track location, you can setup the browser to track this and tag the user with the latitutde and longitude, more details: https://documentation.onesignal.com/docs/location-triggered-event

Tagging

Tag a user based on an event of your choosing so later you can create Segments or Message Personalization. Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time.

iOS SDK implements callbacks to verify tags were successfully added. Android saves tags to device cache and will retry updating the tag automatically upon a stable network connection being established.

sendTag Method

Tag a user based on an app event of your choosing so later you can later create segments to target these users. Use sendTags if you need to set more than one tag on a user at a time.

Parameter

Type

Description

key

String, NSString*

Key of your choosing to create or update

value

String, NSString*

Value to set on the key. NOTE: Passing in a blank String deletes the key, you can also call deleteTag or deleteTags.

onSuccess(Optional)

OneSignalResultSuccessBlock

iOS Called if there were no errors sending the tag.

onFailure(Optional)

OneSignalFailureBlock

iOS Called if there was an error.

Android Will retry automatically upon a stable network connection.

OneSignal.sendTag("key", "value");
OneSignal.sendTag("key", value: "value")
[OneSignal sendTag:@"key" value:@"value"];
OneSignal.SendTag("key", "value");
OneSignal.sendTag("key", "value");
window.plugins.OneSignal.sendTag("key", "value");
await OneSignal.shared.sendTag("test", "value");
OneSignal.Current.SendTag("key", "value");
OneSignal.SendTag("CoronaTag1", "value1")
OneSignal.push(function() {         
  OneSignal.sendTag("key", "value", function(tagsSent) {
    // Callback called when tags have finished sending
  });
});

sendTags Method

Tag a user based on an app event of your choosing, so that later you can create segments to target these users.

Parameter

Type

Description

keyValues

JSONObject, NSDictionary*

Key value pairs of your choosing to create or update. NOTE: Passing in a blank NSString* as a value deletes the key, you can also call deleteTag or deleteTags.

onSuccess(Optional)

OneSignalResultSuccessBlock

iOS Called if there were no errors sending the tag.

onFailure(Optional)

OneSignalFailureBlock

iOS Called if there was an error.

Android Will retry automatically upon a stable network connection.

JSONObject tags = new JSONObject();
tags.put("key1", "value1");
tags.put("key2", "value2");
OneSignal.sendTags(tags);
OneSignal.sendTags(["key1": "value1", "key2": "value2"])
[OneSignal sendTags:@{@"key1" : @"value1", @"key2" : @"value2"}];
OneSignal.SendTags(new Dictionary<string, string>() { {"UnityTestKey2", "value2"}, {"UnityTestKey3", "value3"} });
OneSignal.sendTags({key: "value", key2: "value2"});
window.plugins.OneSignal.sendTags({key: "value", key2: "value2"});
await OneSignal.shared.sendTags({"test_key_1" : "test_value_1", "test_key_2" : "test_value_2"});
OneSignal.Current.SendTags(new Dictionary<string, string>() { {"TestKey2", "value2"}, {"TestKey3", "value3"} });
OneSignal.SendTags({["CoronaTag2"] = "value2",["CoronaTag3"] = "value3"})
OneSignal.push(function() {
  OneSignal.sendTags({
    key: 'value',
    key2: 'value2',
  }, function(tagsSent) {
    // Callback called when tags have finished sending    
  });
});

getTags Method

Retrieve a list of tags that have been set on the user from the OneSignal server.
Android will provide a cached copy if there is no network connection.

//The tagsAvailable callback does not return on the Main(UI) Thread, so be aware when modifying UI in this method.
OneSignal.getTags(new GetTagsHandler() {
    @Override
    public void tagsAvailable(JSONObject tags) {
    //tags can be null
    if (tags !== null) {
      Log.d("debug", tags.toString());
    }
  }
});
OneSignal.getTags({ tags in
    print("tags - \(tags!)")
}, onFailure: { error in
    print("Error getting tags - \(error?.localizedDescription)")
})
[oneSignal getTags:^(NSDictionary* tags) {
    NSLog(@"%@", tags);
}];
void SomeMethod() {
        OneSignal.GetTags(TagsReceived);
    }

    private void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }
OneSignal.getTags((receivedTags) => {
    console.log(receivedTags);
})
window.plugins.OneSignal.getTags(function(tags) {
  console.log('Tags Received: ' + JSON.stringify(tags));
});
Map<String, dynamic> tags = await OneSignal.shared.getTags();
void SomeMethod() {
        OneSignal.GetTags(TagsReceived);
    }

    private void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }
function printAllTags(tags)
   for key,value in pairs(tags) do
      print( key, value )
   end
end

OneSignal.GetTags(printAllTags)
OneSignal.push(function() {
  OneSignal.getTags(function(tags) {
    // All the tags stored on the current webpage visitor
  });
});

Parameter

Type

Description

tags

JSON Object

Contains key-value pairs retrieved from the OneSignal server.

successBlock

OneSignalResultSuccessBlock

Called when tags are received from OneSignal's server.

onFailure(Optional)

OneSignalFailureBlock

Called if there was an error.

deleteTag Method

Deletes a single tag that was previously set on a user with sendTag or sendTags. Use deleteTags if you need to delete more than one.

Parameter

Type

Description

key

String, NSString*

Key to remove

onSuccess(Optional)

OneSignalResultSuccessBlock

iOS Called if there were no errors

onFailure(Optional)

OneSignalFailureBlock

iOS Called if there was an error

Android Will retry automatically upon a stable network connection.

OneSignal.deleteTag("key");
OneSignal.deleteTag("key")
[OneSignal deleteTag:@"key"];
OneSignal.DeleteTag("key");
OneSignal.deleteTag("key");
window.plugins.OneSignal.deleteTag("key");
await OneSignal.shared.deleteTag("test");
OneSignal.DeleteTag("key");
OneSignal.DeleteTag("CoronaTag1")
OneSignal.push(function() {
  OneSignal.deleteTag("tagKey");
});

deleteTags Method

Deletes one or more tags that were previously set on a user with sendTag or sendTags.

Parameter

Type

Description

keys

Collection, NSArray*

Keys to remove.

onSuccess(Optional)

OneSignalResultSuccessBlock

iOS Called if there were no errors

onFailure(Optional)

OneSignalFailureBlock

iOS Called if there was an error

Android Will retry automatically upon a stable network connection.

Collection<String> tempList = new ArrayList<String>();
tempList.add(key);
OneSignal.deleteTags(tempList);
OneSignal.deleteTags(["key1", "key2"])
[OneSignal deleteTags:@[@"key1", @"key2"]];
OneSignal.DeleteTags(new List<string>() {"UnityTestKey2", "UnityTestKey3" })
OneSignal.deleteTags("key");
window.plugins.OneSignal.deleteTags(["key1", "key2"]);
await OneSignal.shared.deleteTags(["test_key_1", "test_key_2"]);
OneSignal.Current.DeleteTags(new List<string>() {"TestKey2", "TestKey3" })
OneSignal.DeleteTags({"key1", "key2"})
OneSignal.push(function() {
  OneSignal.deleteTags(["key1", "key2"], function(tagsDeleted) {
    // Callback called when tags have been deleted    
  });
});

Sending Notifications

postNotification Method

Allows you to send notifications from user to user, or schedule notifications in the future to be delivered to the current device.

🚧

User Targeting Warning

You can only use include_player_ids as a targeting parameter from your app. Other target options such as tags and included_segments require your OneSignal App REST API key which can only be used from your server.

See the Create notification REST API POST call for a list of all possible options.

Parameter

Type

Description

parameters

JSONObject, NSDictionary*

Contains notification options, see our Create notification POST call for all options.

try {
  OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + "userId" + "']}"),
     new OneSignal.PostNotificationResponseHandler() {
       @Override
       public void onSuccess(JSONObject response) {
         Log.i("OneSignalExample", "postNotification Success: " + response.toString());
       }

       @Override
       public void onFailure(JSONObject response) {
         Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
       }
     });
} catch (JSONException e) {
  e.printStackTrace();
}
OneSignal.postNotification(["contents": ["en": "Test Message"], "include_player_ids": ["3009e210-3166-11e5-bc1b-db44eb02b120"]])
[OneSignal postNotification:@{
   @"contents" : @{@"en": @"Test Message"},
   @"include_player_ids": @[@"3009e210-3166-11e5-bc1b-db44eb02b120"]
}];
using OneSignalPush.MiniJSON;

private static string oneSignalDebugMessage;

void someMethod() {
// Just an example userId, use your own or get it the devices by using the GetPermissionSubscriptionState method
string userId = "b2f7f966-d8cc-11e4-bed1-df8f05be55ba";

var notification = new Dictionary<string, object>();
notification["contents"] = new Dictionary<string, string>() { {"en", "Test Message"} };

notification["include_player_ids"] = new List<string>() { userId };
// Example of scheduling a notification in the future.
notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U");

OneSignal.PostNotification(notification, (responseSuccess) => {
  oneSignalDebugMessage = "Notification posted successful! Delayed by about 30 secounds to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess);
}, (responseFailure) => {
  oneSignalDebugMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure);
});

}
let otherParameters = {"ios_attachments" : {"image1" : "{image_url}"}};
let data = arr // some array as payload
let contents = {
    'en': 'You got notification from user'
}
OneSignal.postNotification(contents, data, playerId, otherParameters);

// Calling postNotification with external ids only

OneSignal.postNotification(contents, data, null, {include_external_user_ids:[<external_id>, <external_id>, <external_id>]});


// Listening to postNotification using OneSignal.Configure:
onNotificationOpened: function(message, data, isActive) {
    if (data.p2p_notification) {
        for (var num in data.p2p_notification) {
            // console.log(data.p2p_notification[num]);
        }
    }
}
window.plugins.OneSignal.getIds(function(ids) {
  var notificationObj = { contents: {en: "message body"},
                          include_player_ids: [ids.userId]};
  window.plugins.OneSignal.postNotification(notificationObj,
    function(successResponse) {
      console.log("Notification Post Success:", successResponse);
    },
    function (failedResponse) {
      console.log("Notification Post Failed: ", failedResponse);
      alert("Notification Post Failed:\n" + JSON.stringify(failedResponse));
    }
  );
});
var status = await OneSignal.shared.getPermissionSubscriptionState();

var playerId = status.subscriptionStatus.userId;

await OneSignal.shared.postNotification(OSCreateNotification(
  playerIds: [playerId],
  content: "this is a test from OneSignal's Flutter SDK",
  heading: "Test Notification",
  send_after: DateTime.now().add(Duration(minutes: 30)).toUtc().toIso8601String();,
  buttons: [
    OSActionButton(text: "test1", id: "id1"),
    OSActionButton(text: "test2", id: "id2")
  ]
));
using OneSignalPush.MiniJSON;

private static string oneSignalDebugMessage;

void someMethod() {
// Just an example userId, use your own or get it the devices by calling OneSignal.GetIdsAvailable
string userId = "b2f7f966-d8cc-11e4-bed1-df8f05be55ba";

var notification = new Dictionary<string, object>();
notification["contents"] = new Dictionary<string, string>() { {"en", "Test Message"} };

notification["include_player_ids"] = new List<string>() { userId };
// Example of scheduling a notification in the future.
notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U");

OneSignal.Current.PostNotification(notification, (responseSuccess) => {
  oneSignalDebugMessage = "Notification posted successful! Delayed by about 30 secounds to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess);
}, (responseFailure) => {
  oneSignalDebugMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure);
});

}
function IdsAvailable(userID, pushToken)
    if (pushToken) then
        local notification = {
            ["contents"] = {["en"] = "test"}
        }
        notification["include_player_ids"] = {userID}
        
        OneSignal.PostNotification(notification,
            function(jsonData)
                native.showAlert( "DEBUG", "POST OK!!!", { "OK" } )
                local json = require "json"
                print(json.encode(jsonData))
            end,
            function(jsonData)
                native.showAlert( "DEBUG", "POST NOT OK!!!", { "OK" } )
                local json = require "json"
                print(json.encode(jsonData))
            end
        )
    end
end

OneSignal.IdsAvailableCallback(IdsAvailable)
OneSignal.sendSelfNotification(
  /* Title (defaults if unset) */
  "OneSignal Web Push Notification",
  /* Message (defaults if unset) */
  "Action buttons increase the ways your users can interact with your notification.", 
   /* URL (defaults if unset) */
  'https://example.com/?_osp=do_not_open',
  /* Icon */
  'https://onesignal.com/images/notification_logo.png',
  {
    /* Additional data hash */
    notificationType: 'news-feature'
  }, 
  [{ /* Buttons */
    /* Choose any unique identifier for your button. The ID of the clicked button is passed to you so you can identify which button is clicked */
    id: 'like-button',
    /* The text the button should display. Supports emojis. */
    text: 'Like',
    /* A valid publicly reachable URL to an icon. Keep this small because it's downloaded on each notification display. */
    icon: 'http://i.imgur.com/N8SN8ZS.png',
    /* The URL to open when this action button is clicked. See the sections below for special URLs that prevent opening any window. */
    url: 'https://example.com/?_osp=do_not_open'
  },
  {
    id: 'read-more-button',
    text: 'Read more',
    icon: 'http://i.imgur.com/MIxJp1L.png',
    url: 'https://example.com/?_osp=do_not_open'
  }]
);

clearOneSignalNotifications Method

iOS provides a standard way to clear notifications by clearing badge count. There is no specific OneSignal API call for clearing notifications.

OneSignal.clearOneSignalNotifications();
OneSignal.ClearOneSignalNotifications();
OneSignal.clearOneSignalNotifications();
OneSignal.clearOneSignalNotifications();
//Currently not available
OneSignal.Current.ClearOneSignalNotifications();
OneSignal.ClearAllNotifications()
//Not available

Email

setEmail Method

Allows you to set the user's email address with the OneSignal SDK. We offer several overloaded versions of this method.

OneSignal.setEmail("[email protected]");
OneSignal.setEmail("[email protected]");
[OneSignal setEmail:@"[email protected]"];
OneSignal.SetEmail("[email protected]");
var email = "[email protected]";//email you pull from app
var sha_token = null;//pull from your server or keep as null

OneSignal.setEmail(email, sha_token, (error) => {
    //handle error if it occurred
});
window.plugins.OneSignal.setEmail("[email protected]");
OneSignal.shared.setEmail(email: "[email protected]").then((result) {
    //request succeeded
}).catchError((error) {
    //encountered an error
});
OneSignal.Current.SetEmail("[email protected]");

// Optionally, you can also use callbacks
OneSignal.Current.SetEmail("[email protected]", () => {
  //handle success
}, (error) => {
  //handle failure
});
--Not available
OneSignal.setEmail("[email protected]");

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an email authentication token and send it to your app.

Callback example:

String email = "[email protected]";
String emailAuthHash = "..."; // Email auth hash generated from your server
OneSignal.setEmail(email, emailAuthHash, new OneSignal.EmailUpdateHandler() {
  @Override
  public void onSuccess() {
    // Email successfully synced with OneSignal
  }

  @Override
  public void onFailure(OneSignal.EmailUpdateError error) {
    // Error syncing email, check error.getType() and error.getMessage() for details
  }
});
let emailAuthHash = //generated on your backend server
let email = "[email protected]";
OneSignal.setEmail(email, withEmailAuthHashToken: emailAuthHash, withSuccess: {
    //The email has successfully been set.
}) { (error) in
    //Encountered an error while setting the email.
};
NSString *hashToken = //hash token from your server
NSString *emailAddress = @"[email protected]";
[OneSignal setEmail:emailAddress withEmailAuthHashToken:hashToken onSuccess: ^() {
    //The email has successfully been set.
} onFailure: ^(NSError *error) {
    //Encountered an error while setting the email.
}];
string emailAuthToken = ""; //from your backend server

OneSignal.SetEmail("[email protected]", emailAuthToken, () => {
    //Successfully set email
}, (error) => {
    //Encountered error setting email
});
var email = "[email protected]";//email you pull from app
var sha_token = null;//pull from your server or keep as null

OneSignal.setEmail(email, sha_token, (error) => {
    //handle error if it occurred
});
let emailAuthToken = ""; //from your backend server

window.plugins.OneSignal.setEmail("[email protected]", emailAuthToken, function() {
    //Successfully set email

}, function(error) {
    //encountered an error setting email
    
});
String tokenFromServer = "";

OneSignal.shared.setEmail(email: "[email protected]", emailAuthHashToken: tokenFromServer).then((result) {
    //request succeeded
}).catchError((error) {
    //encountered an error
});
string email = "[email protected]";
string emailAuthCode = ; //generated on your backend server
OneSignal.SetEmail(email, emailAuthCode);

// Optionally, you can also use callbacks
OneSignal.Current.SetEmail(email, emailAuthCode, () => {
    //handle success
}, (error) => {
    //handle failure
});
--Not available
var emailAuthHash = "..."; // Email auth hash generated from your server
OneSignal.setEmail("[email protected], {
 emailAuthHash: emailAuthHash
});

OSEmailSubscriptionState

Checks the subscription state of the email address tied to the current device record. You can only use this if you added emails with the setEmail method.

For our Mobile SDK, see getPermissionSubscriptionState.

OneSignal.getEmail();

logoutEmail Method

If your app implements logout functionality, you can call logoutEmail to dissociate the email from the device:

OneSignal.logoutEmail();
OneSignal.logoutEmail();
[OneSignal logoutEmail];
OneSignal.LogoutEmail (() => {
    // Successfully logged out of email
}, (error) => {
    // Encountered error logging out of email
});
OneSignal.logoutEmail({(error) => {
    //handle error if it occurred
}});
window.plugins.OneSignal.logoutEmail(function(successResponse) {
    //Successfully logged out of email
}, function(error) {
    //Failed to log out of email
});
await OneSignal.shared.logoutEmail();
OneSignal.Current.LogoutEmail();

// Optionally, you can also use callbacks
OneSignal.Current.LogoutEmail(() => {
  //handle success
}, (error) => {
  //handle failure
});
--Not available
OneSignal.logoutEmail();

addEmailSubscriptionObserver Method

Tracks changes to email subscriptions (for example, if the user sets their email, or logs out). In order to subscribe to email subscription changes, you can implement the following:

OneSignal.addEmailSubscriptionObserver(subscriptionObserver);
OneSignal.add(self as OSEmailSubscriptionObserver)
[OneSignal addEmailSubscriptionObserver:self];
void Start() {
    OneSignal.emailSubscriptionObserver += OneSignal_emailSubscriptionObserver;
}
// Currently Not Available, let us know you want this!
window.plugins.OneSignal.addEmailSubscriptionObserver(function(stateChanges) {
    //Email subscription state changed
    let newEmailAddress = stateChanges.to.emailAddress;
    let newUserId = stateChanges.to.emailUserId;
});
//More Details: https://documentation.onesignal.com/docs/flutter-sdk#section--osemailsubscriptionstate-
//Also see: https://documentation.onesignal.com/docs/flutter-sdk#section--osemailsubscriptionstatechanges-
//Currently not available
-- Not available
//Not available

Now, whenever the email subscription changes, this method will be called:

OSEmailSubscriptionObserver subscriptionObserver = new OSEmailSubscriptionObserver() {
   @Override
   public void onOSEmailSubscriptionChanged(OSEmailSubscriptionStateChanges stateChanges) {
   }
};
func onOSEmailSubscriptionChanged(_ stateChanges: OSEmailSubscriptionStateChanges!) { 
    
}
-(void)onOSEmailSubscriptionChanged:(OSEmailSubscriptionStateChanges *)stateChanges {
    
}
private void OneSignal_emailSubscriptionObserver(OSEmailSubscriptionStateChanges stateChanges) {
    string newEmailAddress = stateChanges.to.emailAddress;
}
// Currently Not Available, let us know you want this!
window.plugins.OneSignal.addEmailSubscriptionObserver(function(stateChanges) {
    //Email subscription state changed
    let newEmailAddress = stateChanges.to.emailAddress;
    let newUserId = stateChanges.to.emailUserId;
});
//More Details: https://documentation.onesignal.com/docs/flutter-sdk#section--osemailsubscriptionstate-
//Also see: https://documentation.onesignal.com/docs/flutter-sdk#section--osemailsubscriptionstatechanges-
//Currently not available
-- Not available
//Not available

In-App Messages

Check out In-App Messaging Quickstart to get an overview before diving into the SDK methods below.

In-App Triggers

Triggers are events that you fire to show In-App Messages within your app. They are created within the OneSignal Dashboard.

Every time you add or remove a trigger with the below methods, the OneSignal SDK will evaluate if an In-App Message should be shown based on the conditions set on it when it was created in the OneSignal Dashboard.

Triggers are reset each time your app is closed, so make sure to set them again when starting your app if you need any of them to be persistent.

addTrigger Method

Add a trigger. May show an In-App Message if its trigger conditions were met.

Parameter

Type

Description

key

String, NSString

Key for the trigger.

value

Object, id
(String or number recommended)

Value for the trigger.
Object passed in will be converted to a string.

OneSignal.addTrigger("level", 5);
OneSignal.addTrigger("prompt_ios", withValue: "true");
[OneSignal addTrigger:@"product" withVaue:@"aggieTee"]
// Add a single trigger
OneSignal.AddTrigger("key", "value");
OneSignal.addTrigger("level", 5);
window.plugins.OneSignal.addTrigger("level", 5);
OneSignal.shared.addTrigger("level", 5);
OneSignal.Current.AddTrigger("trigger_1", "one");
--Currently IAM not available for Corona
//Currently IAM not available for Web, let us know your interested!

addTriggers Method

Add a map of triggers. May show an In-App Message if its trigger conditions were met.

Parameter

Type

Description

triggers

Map<String, Object>, NSDictionary<NSString *, id>

Allows you to set multiple trigger key/value pairs simultaneously.

HashMap<String, Object> testTriggers = new HashMap<>();
testTriggers.put("test1", "value1");
testTriggers.put("test2", "value2");

OneSignal.addTriggers(testTriggers);
OneSignal.addTriggers(["checkoutStep":"3", "product":"aggieHat"])
NSDictionary *triggers = @{
    @"checkoutStep": @"3",
    @"product": @"aggieHat"
};

[OneSignal addTriggers:triggers]
NSDictionary *triggers = @{
    @"checkoutStep": @"3",
    @"product": @"aggieHat"
};

[OneSignal addTriggers:triggers]
OneSignal.addTriggers({"isLonghorn":"true", "clicked":"true"});
window.plugins.OneSignal.addTriggers({"isAggie":"true", "clicked":"true"});
Map<String, Object> triggers = new Map<String, Object>();
triggers["trigger_2"] = "two";
triggers["trigger_3"] = "three";
OneSignal.shared.addTriggers(triggers);
Dictionary<string, object> triggers = new Dictionary<string, object>();
triggers.Add("trigger_2", "two");
triggers.Add("trigger_3", "three");
OneSignal.Current.AddTriggers(triggers);
--Currently IAM not available for Corona
//Currently IAM not available for Web, let us know your interested!

removeTriggerForKey Method

Removes a single trigger for the given key. May show an In-App Message if its trigger conditions were met.

Parameter

Type

Description

key

String, NSString

Key for trigger to remove.

OneSignal.removeTriggerForKey("level");
OneSignal.removeTriggerForKey("product");
[OneSignal removeTriggerForKey:@"product"]
// Delete a trigger
OneSignal.RemoveTriggerForKey("key");
OneSignal.removeTriggerForKey("isLonghorn");
window.plugins.OneSignal.removeTriggerForKey("isAggie");
OneSignal.shared.removeTriggerForKey("isAggie");
OneSignal.Current.RemoveTriggerForKey("trigger_2");
--Currently IAM not available for Corona
//Currently IAM not available for Web, let us know your interested!

removeTriggersForKeys Method

Removes a list of triggers based on a collection of keys. May show an In-App Message if its trigger conditions were met.

Parameter

Type

Description

keys

Collection

Removes a collection of triggers from their keys.

getTriggerValueForKey Method

Gets a trigger value for a provided trigger key.

Parameter

Type

Description

key

String, NSString

Returns a single trigger value for the given key,
if it exists, otherwise returns null or nil in iOS.

Return Type

Description

Object (Android)
id (iOS)
String (Unity)

Value if added with addTrigger, or null/nil (iOS) if never set.

Object triggerValue;
triggerValue = OneSignal.getTriggerValueForKey("level");
OneSignal.getTriggerValueForKey("product");
[OneSignal getTriggerValueForKey:@"product"]
// Get the current value to a trigger by key
var triggerValue = OneSignal.GetTriggerValueForKey("key");
OneSignal.getTriggerValueForKey("isLonghorn", function (value) {
  console.log("isLonghorn:", value)
});
window.plugins.OneSignal.getTriggerValueForKey("isAggie", function (value) {
  console.log("isAggie:", value)
});
Object triggerValue = await OneSignal.shared.getTriggerValueForKey("myTrigger");
print("myTrigger key trigger value: " + triggerValue);
object value = OneSignal.Current.GetTriggerValueForKey("trigger_1");
Debug.WriteLine("trigger_1 value: " + value);
--Currently IAM not available for Corona
//Currently IAM not available for Web, let us know your interested!

pauseInAppMessages Method

Allows you to temporarily pause all In-App Messages. You may want to do this while the user is engaged in an activity that you don't want a message to interrupt (such as watching a video).

Parameter

Type

Description

pause

Boolean

To pause, set true.
To resume, set false.

setInAppMessageClickHandler Method

Sets a In-App Message opened handler. The instance will be called when an In-App Message action is tapped on.

Parameter

Type

Description

handler

InAppMessageClickHandler - Android
OSHandleInAppMessageActionClickBlock - iOS

Instance to a class implementing this interference.

OneSignal.startInit(this)   
   .setInAppMessageClickHandler(new InAppMessageClickHandler())
   .init();
let handler: OSHandleInAppMessageActionClickBlock = { action in
    var message: String? = nil
    if let clickName = action?.clickName, let clickUrl = action?.clickUrl, let firstClick = action?.firstClick, let closesMessage = action?.closesMessage {
        message = String(format: "Click Action Occurred: clickName:%@ clickUrl:%@ firstClick:%i closesMessage:%i", clickName, clickUrl as CVarArg, firstClick, closesMessage)
        print(message ?? "no message")
    }
}

OneSignal.setInAppMessageClickHandler(handler)
id handler = ^(OSInAppMessageAction *action) {
        NSString *message = [NSString stringWithFormat:@"Click Action Occurred: clickName:%@ clickUrl:%@ firstClick:%i closesMessage:%i",
                             action.clickName,
                             action.clickUrl,
                             action.firstClick,
                             action.closesMessage];
        [OneSignal onesignal_Log:ONE_S_LL_DEBUG message:message];
    };

[OneSignal setInAppMessageClickHandler:handler]
OneSignal.StartInit("YOUR_ONESIGNAL_APP_ID")
               .HandleInAppMessageClicked(HandleInAppMessageClicked)
               .EndInit();
componentWillMount() {
    OneSignal.addEventListener('inAppMessageClicked', this.onInAppClicked);
}

componentWillUnmount() {
    OneSignal.removeEventListener('inAppMessageClicked', this.onInAppClicked);
}

onInAppClicked(action) {
   let {clickUrl, clickName, firstClick, closesMessage} = action;
   // ...
}
window.plugins.OneSignal
    .startInit("706eae1b-7c2c-4y92-907d-c90dz6416a63")
    .handleInAppMessageClicked(function(action){
    let firstClick = action.first_click;
    let closesMessage = action.closes_message;
    let clickUrl = action.click_url;
    let clickName = action.click_name;
}).endInit();
OneSignal.shared
    .setInAppMessageClickedHandler((OSInAppMessageAction action) {
      // in app message element was clicked (image, button, or body)
    });
OneSignal.Current.StartInit("b0f7f966-d8ec-11e4-bed1-df8f05je55ba").Settings(new Dictionary<string, bool>() {
            { IOSSettings.kOSSettingsKeyAutoPrompt, false },
            { IOSSettings.kOSSettingsKeyInAppLaunchURL, true } })
           .HandleInAppMessageClicked((action) =>
           {
              // Example IAM click handling for IAM elements
              Debug.WriteLine("HandledInAppMessageClicked: {0}", action.clickName);
           })
           .EndInit();
--Currently IAM not available for Corona
//Currently IAM not available for Web, let us know your interested!

InAppMessageClickHandler Handler

Use to process an In-App Message the user just tapped on.

Parameter

Type

Description

result

OSInAppMessageAction

Details about the In-App Message action element (button or image) that was tapped on.

class ExampleInAppMessageClickHandler implements OneSignal.InAppMessageClickHandler {
      // Example of an action id you could setup on the dashboard when creating the In App Message
      private static final String ACTION_ID_MY_CUSTOM_ID = "MY_CUSTOM_ID";

      @Override
      public void inAppMessageClicked(OSInAppMessageAction result) {
         if (ACTION_ID_MY_CUSTOM_ID.equals(result.clickName)) {
            Log.i("OneSignalExample", "Custom Action took place! Starting YourActivity!");
            Intent intent = new Intent(getApplicationContext(), YourActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent);
         }
      }
   }
let handler: OSHandleInAppMessageActionClickBlock = { action in
    if let clickName = action?.clickName {
        print("clickName string: ", clickName)
    }
    if let clickUrl = action?.clickUrl {
        print ("clickUrl string: ", clickUrl)
    }
    if let firstClick = action?.firstClick {
        print("firstClick bool: ", firstClick)
    }
    if let closesMessage = action?.closesMessage {
        print("closesMessage bool: ", closesMessage)
    }
}

OneSignal.setInAppMessageClickHandler(handler)
id handler = ^(OSInAppMessageAction *action) {
        NSString *message = [NSString stringWithFormat:@"Click Action Occurred: clickName:%@ clickUrl:%@ firstClick:%i closesMessage:%i",
                             action.clickName,
                             action.clickUrl,
                             action.firstClick,
                             action.closesMessage];
        [OneSignal onesignal_Log:ONE_S_LL_DEBUG message:message];
    };

[OneSignal setInAppMessageClickHandler:handler]
public static void HandleInAppMessageClicked(OSInAppMessageAction action) {
    String logInAppClickEvent = "In-App Message opened with action.clickName " + action.clickName;
    print(logInAppClickEvent);
    extraMessage = logInAppClickEvent;
}
componentWillMount() {
    OneSignal.addEventListener('inAppMessageClicked', this.onInAppClicked);
}

componentWillUnmount() {
    OneSignal.removeEventListener('inAppMessageClicked', this.onInAppClicked);
}

onInAppClicked(action) {
   let {clickUrl, clickName, firstClick, closesMessage} = action;
   // ...
}
window.plugins.OneSignal
    .startInit("706eae1b-7c2c-4y92-907d-c90dz6416a63")
    .handleInAppMessageClicked(function(action){
    let firstClick = action.first_click;
    let closesMessage = action.closes_message;
    let clickUrl = action.click_url;
    let clickName = action.click_name;
}).endInit();
OneSignal.shared
    .setInAppMessageClickedHandler((OSInAppMessageAction action) {
      // in app message element was clicked (image, button, or body)
    });
OneSignal.Current.StartInit("b0f7f966-d8ec-11e4-bed1-df8f05je55ba").Settings(new Dictionary<string, bool>() {
            { IOSSettings.kOSSettingsKeyAutoPrompt, false },
            { IOSSettings.kOSSettingsKeyInAppLaunchURL, true } })
           .HandleInAppMessageClicked((action) =>
           {
              // Example IAM click handling for IAM elements
              Debug.WriteLine("HandledInAppMessageClicked: {0}", action.clickName);
           })
           .EndInit();
--Currently IAM not available for Corona
//Currently IAM not available for Web, let us know your interested!

OSInAppMessageAction Class

Details about the In-App Message action element (button or image) that was tapped on.

Field

Type

Description

clickName

String, NSString

An optional click name defined for the action element.
null or nil (iOS) if not set

clickUrl

String, NSString

An optional URL that opens when the action takes place.
null or nil (iOS) if not set.

firstClick

Boolean

true if this is the first time the user has pressed
any action on the In-App Message.

closesMessage

Boolean

If
true, the In App Message will animate off the screen. If
false, the In App Message will stay on screen until the user dismisses it.


Updated 16 days ago



SDK Reference


Comprehensive reference of OneSignal's SDK methods

Suggested Edits are limited on API Reference Pages

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