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

Unity SDK

OneSignal Unity SDK Reference.
Works with iOS, Android, Amazon.

📘

Just starting with Unity?

Check out our Unity SDK Setup guide.

Parameter

Data Type

Description

Debugging

setLogLevel

Method

Enable logging to help debug OneSignal implementation.

Initialization

StartInit

Method

Starts initialization of OneSignal, call this on Start method of the first scene that loads. See Unity SDK Setup for details and code examples.

inFocusDisplaying

Method

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

Settings

Method

iOS - Automatically Prompt Users to Enable Notifications and Open all URLs in In-App Safari Window

EndInit

Method

Must be called after StartInit to complete initialization of OneSignal.

Handling Notifications

NotificationReceived

Method

Adds an observer function/callback that will get executed whenever a new OneSignal push notification is received on the device when app is in the foreground.

NotificationOpened

Method

When a user takes an action on a notification

Privacy

setRequiresUserPrivacyConsent

Method

Delays initialization of the SDK until the user provides privacy consent

UserDidProvideConsent

Method

Android, iOS - Provides privacy consent

iOS Prompting

promptForPushNotificationsWithUserResponse

Method

Prompt the user for notification permissions. Callback fires as soon as the user accepts or declines notifications.

Must set kOSSettingsKeyAutoPrompt to false when calling initWithLaunchOptions.

Recommended: Set to false and follow iOS Push Opt-In Prompt.

User Status

getPermissionSubscriptionState

Method

Get the current notification and permission state. Returns a OSPermissionSubscriptionState type.

addPermissionObserver

Event Delegate

Permission status changes

addSubscriptionObserver

Event Delegate

Subscription status changes

setSubscription

Method

Disable OneSignal from sending notifications to current device.

External User IDs

setExternalUserId

Method

Allows you to use your own system's user ID's to send push notifications to your users. To tie a user to a given user ID, you can use this method.

removeExternalUserId

Method

Removes whatever was set as the current user's external user ID.

Tagging

getTags

Method

View Tags from current device record.

sendTag

Method

Add a single Data Tag to current device record.

sendTags

Method

Add multiple Data Tags to current device record.

deleteTag

Method

Delete a Tag from current device record.

deleteTags

Method

Delete multiple Tags from current device record.

Location Data

setLocationShared

Method

Disable or Enable SDK location collection. See Handling Personal Data.

promptLocation

Method

Prompt Users for Location Not Recommended

Recommended: Use In-App Message Location Opt-In Prompt.

Sending Notifications

postNotification

Method

Send or schedule a notification to a OneSignal Player ID.

cancelNotification

Method

Delete a single app notification

clearOneSignalNotifications

Method

Delete all app notifications

In-App Messaging

addTrigger

Method

Add a trigger, may show an In-App Message if its triggers conditions were met.

addTriggers

Method

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

removeTriggerForKey

Method

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

getTriggerValueForKey

Method

Gets a trigger value for a provided trigger key.

pauseInAppMessages

Method

Allows you to temporarily pause all In App Messages.

setInAppMessageClickHandler

Method

Sets an In App Message opened block

Email

setEmail

Method

Set user's email. Creates a new user record for the email address. Use sendTag if you want to update a push user record with the email.

logoutEmail

Method

Log user out to dissociate email from device

addEmailSubscriptionObserver

Method

Observer for subscription changes to email

Notification Objects

OSNotificationOpenedResult

Class

Information returned from a notification the user received.

OSNotification

Class

Represents a received push notification

OSNotificationAction

Class

How user opened notification

OSNotificationPayload

Class

Data that comes with a notification

Appearance

enableVibrate

Method

Android - When user receives notification, vibrate device less

enableSound

Method

Android - When user receives notification, do not play a sound

Initialization

Settings

Method

Settings that can be passed into the initialization chaining method.

Settings key options are:

  • OneSignal.kOSSettingsAutoPrompt - Auto prompt user for notification permissions.
  • OneSignal.kOSSettingsInAppLaunchURL - Launch notifications with a launch URL as an in app webview.

Parameter

Type

Description

settings

Dictionary<string, bool>

Additional initialization settings. Set true or false.


Privacy

SetRequiresUserPrivacyConsent

Method

Allows you to delay the initialization of the SDK until the user provides privacy consent. The SDK will not be fully initialized until the UserDidProvideConsent(true) method is called. The SDK will remember the answer to the last time UserDidProvideConsent was called so you only need to call it once.

If you set this to be true, the SDK will not fully initialize until consent is provided. You can still call OneSignal methods, but nothing will happen, and the user will not be registered for push notifications.

void YourAppInitMethod() {
  // SetRequiresUserPrivacyConsent will prevent
  //   initialization until UserDidProvideConsent(true) is called
  OneSignal.StartInit("YOUR_APP_ID")
    .SetRequiresUserPrivacyConsent(true)
    .EndInit();
}

UserDidProvideConsent

Method

If your application is set to require the user's privacy consent, you can provide this consent using this method. Until you call UserDidProvideConsent(true), the SDK will not fully initialize and will not send any data to OneSignal. The SDK will remember the answer to the last time UserDidProvideConsent was called so you only need to call it once.

void UserAcceptedConsent() {
   // Only needs to be called once,
   //   OneSignal will remember the last answer 
   OneSignal.UserDidProvideConsent(true);
}

UserProvidedConsent

Method

Returns a boolean indicating if the user has given privacy consent yet.

Prompting

PromptForPushNotificationsWithUserResponse

Method - iOS

Call this when you would like to prompt an iOS user to accept push notifications with the default system prompt. Only use if you passed false to autoRegister when calling Init.

OneSignal.PromptForPushNotificationsWithUserResponse(OneSignal_promptForPushNotificationsReponse);

private void OneSignal_promptForPushNotificationsReponse(bool accepted) {
  Debug.Log("OneSignal_promptForPushNotificationsReponse: " + accepted);
}

Status

GetPermissionSubscriptionState

Method

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

permissionStatus

OSPermissionState

Device's Notification Permissions state

subscriptionStatus

OSSubscriptionState

Push Protocol and OneSignal subscription state

var status = OneSignal.GetPermissionSubscriptionState();
status.permissionStatus.hasPrompted;
status.permissionStatus.status;

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

permissionObserver

Event Delegate

Delegate will be fired 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/disabling notifications for your app in the Device's Settings after returning to your app.

Example

Output is showings the user accepting the notification permission prompt.

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

subscriptionObserver

Event Delegate

Delegate will be fired when a notification subscription property changes.

This includes the following events:

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

Example

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

Tags

GetTags

Method

Retrieve a list of tags that have been set on the player from the OneSignal server.

Parameter

Type

Description

inTagsReceivedDelegate

TagsReceived

Delegate gets called once the tags are available.

void SomeMethod() {
        OneSignal.GetTags(TagsReceived);
    }

    private void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }

TagsReceived

Delegate

Delegate you can define to get the all the tags set on a player from onesignal.com.

Parameter

Type

Description

tags

Dictionary<string, object>

Dictionary of key value pairs retrieved from the OneSignal server.

private static void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }

SendTag

Method

Tag a player based on a game event of your choosing so later you can create segments on onesignal.com to target these players. If you need to set more than one key at a time please use SendTags instead.

Parameter

Type

Description

key

String

Key of your choosing to create or update.

value

String

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

OneSignal.SendTag("key", "value");

SendTags

Method

Set multiple tags on a player with one call.

Parameter

Type

Description

tags

Dictionary<string, string>

An IDictionary of key value pairs. NOTE: Passing in a blank as a value deletes the key, you can also call DeleteTag or DeleteTags.

OneSignal.SendTags(new Dictionary<string, string>() { {"UnityTestKey2", "value2"}, {"UnityTestKey3", "value3"} });

DeleteTag

Method

Deletes a tag that was previously set on a player with SendTag or SendTags. Please use DeleteTags if you need to delete more than one tag.

Parameter

Type

Description

key

String

Key to remove.

OneSignal.DeleteTag("key");

DeleteTags

Method

Deletes tags that were previously set on a player with SendTag or SendTags.

Parameter

Type

Description

keys

IList

Keys to remove.

OneSignal.DeleteTags(new List<string>() {"UnityTestKey2", "UnityTestKey3" })

Data

PromptLocation

Method

Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.

OneSignal.PromptLocation();
iOS INSTRUCTIONS

You must add all of the following to your iOS plist settings:

NSLocationUsageDescription

NSLocationWhenInUseUsageDescription

ANDROID INSTRUCTIONS

You must add one of the following Android Permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

SetLocationShared

Method

Accepts a boolean parameter, allows you to enable or disable OneSignal SDK location tracking. Please note that if you disable location tracking, you will not be able to use location based push notifications.

//disables location features
OneSignal.SetLocationShared(false);

Receiving Notifications

PostNotification

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

Parameter

Type

Description

parameters

Dictionary<string, object>

Dictionary of notification options, see our Create notification POST call for all options.

Returns

Method

onSuccess

OnPostNotificationSuccess delegate fires when the notification was created on OneSignal's server.

Dictionary<string, object> - Json response from OneSignal's server.

onFailure

OnPostNotificationFailure delegate fires when the notification failed to create

Dictionary<string, object> - Json response from OneSignal's server.

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

}
import OneSignalPush.MiniJSON;

private static var oneSignalDebugMessage : String;

function someFunction() {
// Just an example userId, use your own or get it the devices by calling OneSignal.GetIdsAvailable
var userId = "b2f7f966-d8cc-11e4-bed1-df8f05be55ba";
var notification = new Dictionary.<String, Object>();
notification["contents"] = {"en": "Test Message" };

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

OneSignal.PostNotification(notification, function(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);
}, function(responseFailure) {
  oneSignalDebugMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure);
});

}

See the Create notification REST API POST call for a list of all possible options. Note: 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.

Canceling a Notification

After creating the notification using postNotification you can save the notification id from the responseSuccess callback to use for canceling the push if required.

Using the API Cancel notification endpoint, you can use something like this to cancel that push if needed through the SDK.

string url = "https://onesignal.com/api/v1/notifications/" + notificationId.ToString() + "?app_id=" + appId;

WebRequest request = WebRequest.Create(url);
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };
request.Method = "DELETE";
request.GetResponse();
import OneSignalPush.MiniJSON;

private static var oneSignalDebugMessage : String;

function someFunction() {
// Just an example userId, use your own or get it the devices by calling OneSignal.GetIdsAvailable
var userId = "b2f7f966-d8cc-11e4-bed1-df8f05be55ba";
var notification = new Dictionary.<String, Object>();
notification["contents"] = {"en": "Test Message" };

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

OneSignal.PostNotification(notification, function(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);
}, function(responseFailure) {
  oneSignalDebugMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure);
});

}

ClearOneSignalNotifications

Removes all OneSignal app notifications from the Notification Shade.

OneSignal.ClearOneSignalNotifications();

SetSubscription

Method

You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications.

Parameter

Type

enable

Boolean

OneSignal.SetSubscription(false);

setEmail

Method

setEmail 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]");

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. The following code also includes callbacks:

string emailAuthToken = ""; //from your backend server

OneSignal.SetEmail("[email protected]", emailAuthToken, () => {
    //Successfully set email
}, (error) => {
    //Encountered error setting email
});

logoutEmail

Method

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

OneSignal.LogoutEmail (() => {
    // Successfully logged out of email
}, (error) => {
    // Encountered error logging out of email
});

addEmailSubscriptionObserver

Method

We have also added a new email subscription observer to track changes to email subscriptions (ie. the user sets their email or logs out). In order to subscribe to email subscription changes you can implement the following:

void Start() {
    OneSignal.emailSubscriptionObserver += OneSignal_emailSubscriptionObserver;
}

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

private void OneSignal_emailSubscriptionObserver(OSEmailSubscriptionStateChanges stateChanges) {
    string newEmailAddress = stateChanges.to.emailAddress;
}

External ID's

setExternalUserId

Method

If your system assigns unique identifiers to users, it can be annoying to have to also remember their OneSignal user ID's as well. To make things easier, OneSignal now allows you to set an external_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 myCustomUniqueUserId = "something from my backend server";
  
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.

//usually called after the user logs out of your app
OneSignal.RemoveExternalUserId();

Notification Events

NotificationReceived

Method

Use to process a OneSignal notification that was just received while the app was in focus.

Parameter

Type

Description

result

OSNotification

Object containing properties of the notification.

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;
}
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(notification : OSNotification) {
  payload : OSNotificationPayload = notification.payload;
  message : String = payload.body;

  print("GameControllerExample:HandleNotificationReceived: " + message);
  print("displayType: " + notification.displayType);
  extraMessage = "Notification received with text: " + message;
}

NotificationOpened

Method

Use to process a OneSignal notification the user just tapped on.

Parameter

Type

Description

result

OSNotificationOpenedResult

Object containing both the user's response and properties of the notification.

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, string> 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;
  }
}
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 function HandleNotificationOpened(result : OSNotificationOpenedResult) : Void {
  OSNotificationPayload payload = result.notification.payload;
  additionalData : Dictionary.<String, String> = payload.additionalData;
  message : String = payload.body;
  actionID : String = 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;
  }
}

OSNotificationOpenedResult

Class

The information returned from a notification the user received.

Parameter

Type

Description

notification

OSNotification

Notification the user opened.

action

OSNotificationAction

The action the user took on the notification.

OSNotification

Class

The notification the user opened.

Parameter

Type

Description

isAppInFocus

boolean

Was app in focus.

shown

boolean

Was notification shown to the user. Will be false for silent notifications.

androidNotificationId

int

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

payload

OSNotificationPayload

Payload received from OneSignal.

displayType

DisplayType

How the notification was displayed to the user.

groupedNotifications

List<OSNotificationPayload>

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

displayType

Object

How the notification was displayed to the user. Part of OSNotification. See InFocusDisplaying for more information on how this is used.

Notification - native notification display.
InAppAlert (Default) - native alert dialog display.
None - notification is silent, or InFocusDisplaying is disabled.

OSNotificationAction

Class

The action the user took on the notification.

Parameter

Type

Description

type

ActionType

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

actionID

String

If type == ActionTaken then this will contain the id of the button pressed.

OSNotificationPayload

Class

Contents and settings of the notification the user received.

Parameter

Type

Description

notificationId

String

OneSignal notification UUID.

title

String

Title of the notification.

body

String

Body of the notification.

additionalData

JSONObject

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.

smallIcon

String

Small icon resource name set on the notification.

largeIcon

String

Large icon set on the notification.

bigPicture

String

Big picture image set on the notification.

smallIconAccentColor

String

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

launchUrl

String

URL to open when opening the notification.

sound

String

Sound resource to play when the notification is shown.

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 = Public (fully visible)(default), 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>

List of action buttons on the notification.

fromProjectNumber

String

The Google project number the notification was sent under.

backgroundImageLayout

BackgroundImageLayout

If a background image was set this object will be available.

rawPayload

String

Raw JSON payload string received from OneSignal.

ActionButton

Object

List of action buttons on the notification. Part of OSNotificationPayload.

Parameter

Type

Description

id

String

Id assigned to the button.

text

String

Text show on the button to the user.

icon

String

Icon shown on the button.

BackgroundImageLayout

Object - Android

If a background image was set, this object will be available. Part of OSNotificationPayload.

Parameter

Type

Description

image

String

Image URL or name used as the background image.

titleTextColor

String

Text color of the title on the notification. ARGB Format.

bodyTextColor

String

Text color of the body on the notification. ARGB Format.

Appearance

EnableVibrate

Method - Android

By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.

You can link this action to a UI button to give your user a vibration option for your notifications.

OneSignal.EnableVibrate(false);

EnableSound

Method - Android

By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.

You can link this action to a UI button to give your user a different sound option for your notifications.

OneSignal.EnableSound(false);

In-App Messaging

addTrigger

Method

Add a trigger, may show an In-App Message if its triggers conditions were met.

Parameter

Type

Description

key

String

Key for the trigger

value

Object (String or Number Recommended)

Value of the trigger.
Object passed in will have toString()called if not a String

Example

// Add a single trigger
OneSignal.AddTrigger("key", "value");

addTriggers

Method

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

Parameter

Type

Description

triggers

Map<String, Object>

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

removeTriggerForKey

Method

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

Example

Parameter

Type

Description

key

String

Key for trigger remove

// Delete a trigger
OneSignal.RemoveTriggerForKey("key");

removeTriggersForKeys

Method

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

Parameter

Type

Description

keys

Collection<String>

Removes a collection of triggers from their keys

getTriggerValueForKey

Method

Gets a trigger value for a provided trigger key.

Parameter

Type

Description

key

String

Returns a single trigger value for the given key,
if it exists, otherwise returns null

Return Type

String

Value if added with addTrigger or null if never set.

Example

// Get the current value to a trigger by key
var triggerValue = OneSignal.GetTriggerValueForKey("key");

pauseInAppMessages

Method

Allows you to temporarily pause all In App Messages. You may want to do this while the user is watching a video playing a match in your game to make sure they don't get interrupted at a bad time.

Parameter

Type

Description

pause

boolean

To pause set true
To resume set false

HandleInAppMessageClicked

Builder 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

InAppMessageClicked

Instance to a class implementing this interference.

Example

OneSignal.StartInit("YOUR_ONESIGNAL_APP_ID")
               .HandleInAppMessageClicked(HandleInAppMessageClicked)
               .EndInit();

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.

Example

public static void HandleInAppMessageClicked(OSInAppMessageAction action) {
    String logInAppClickEvent = "In-App Message opened with action.clickName " + action.clickName;
    print(logInAppClickEvent);
    extraMessage = logInAppClickEvent;
}

OSInAppMessageAction

Class

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

Field

Type

Description

clickName

String

An optional click name defined for the action element.
null if not set

clickUrl

String

An optional URL that opens when the action takes place.
null 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

Did the action close the In App Message.
true - In App Message will animate off the screen.
false - In App Message will stay on screen until the user dismisses.

Updated about a month ago


Unity SDK


OneSignal Unity SDK Reference.
Works with iOS, Android, Amazon.

Suggested Edits are limited on API Reference Pages

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