SDK Reference
Comprehensive reference of OneSignal's SDK methods
Debugging
setLogLevel
Method
setLogLevel
MethodEnable 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)
Initialization Settings
App In-Focus Notification Display
Deprecated in Major Release SDKs
If using the following OneSignal SDK Versions, use the updated methods outlined in the Updated SDK Reference:
- Android 4.0.0+
- iOS 3.0.0+
- React Native 4.0.0+
- Flutter 3.0.0+
- Cordova/Ionic 3.0.0+
Setting to control how OneSignal notifications will be shown when one is received while your app is in focus.
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 Alert Prompt that must be displayed and the user must authorize permission for your app to send them push notifications. iOS also supports Provisional Push Notifications.
You can display this Alert using the OneSignal SDK in 2 ways:
- Recommended: use OneSignal's In-App Message Soft-Prompt before displaying the Native Alert. Details: iOS Push Opt-In Prompt Guide.
- Programmatically Trigger the Native Alert Prompt with the OneSignal SDK
promptForPushNotifications
method.
OneSignal Notification Events
Notification Received Handler
Called when the app receives a notification.
Deprecated in Major Release SDKs
If using the following OneSignal SDK Versions, use the updated methods outlined in the Updated SDK Reference:
- Android 4.0.0+
- iOS 3.0.0+
- React Native 4.0.0+
- Flutter 3.0.0+
- Cordova/Ionic 3.0.0+
Method called in following cases:
- Android Native SDK when the app receives a notification while foregrounded or backgrounded.
- iOS Native SDK when the app receives a notification while in the foreground only. If you need this to be called when your app is in the background, set
content_available
totrue
when you create your notification. The "force-quit" state (for example, if the app was swiped away) is not currently supported. - Non-native SDKs when the app receives a notification while in the foreground only. To handle the notification while the app is not in the foreground, you must use the Service Extensions.
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);
}
}
//See: https://documentation.onesignal.com/docs/react-native-sdk#setnotificationopenedhandler-function
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 DisplayedInAppAlert - 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
getPermissionSubscriptionState
MethodDeprecated in Major Release SDKs
If using the following OneSignal SDK Versions, use the updated methods outlined in the Updated SDK Reference:
- Android 4.0.0+
- iOS 3.0.0+
- React Native 4.0.0+
- Flutter 3.0.0+
- Cordova/Ionic 3.0.0+
Get the current notification and permission state. Returns a OSPermissionSubscriptionState
type, as described below.
OSPermissionSubscriptionState
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()
// Push Status Methods
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)
if let userID = status.subscriptionStatus.userId{
print("userID: ", userID)
}
if let pushToken = status.subscriptionStatus.pushToken {
print("pushToken: ", pushToken)
}
// Email Status Methods
if let emailPlayerId = status.emailSubscriptionStatus.emailUserId {
print("emailPlayerId: ", emailPlayerId)
}
if let emailAddress = status.emailSubscriptionStatus.emailAddress {
print("emailAddress: ", emailAddress)
}
let isEmailSubscribed = status.emailSubscriptionStatus.subscribed
print("isEmailSubscribed: ", isEmailSubscribed)
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)
OneSignal.push(function() {
OneSignal.getUserId(function(userId) {
console.log("OneSignal User ID:", userId);
// (Output) OneSignal User ID: 270a35cd-4dda-4b3f-b04e-41d7463a2316
});
OneSignal.getEmailId(function(emailId) {
console.log("OneSignal Email ID:", emailId);
// (Output) OneSignal Email ID: 07f6c3e0-531c-450a-8274-a17a80e0db4b
});
});
addPermissionObserver
Method
addPermissionObserver
MethodThe 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
});
addSubscriptionObserver
Method
addSubscriptionObserver
MethodWeb 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
The 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);
});
});
disablePush
Method
disablePush
MethodThe 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 true to opt out users from receiving notifications through OneSignal. You can pass false later to opt users back into notifications.
// Android SDK version 4.x.x
OneSignal.disablePush(true);
//Android SDK version 3.x.x
OneSignal.setSubscription(false);
// iOS SDK 3.x.x use
OneSignal.disablePush(true)
// iOS SDK 2.x.x use
OneSignal.setSubscription(false)
// iOS SDK 3.x.x use
[OneSignal disablePush:true];
// iOS SDK 2.x.x use
[OneSignal setSubscription:false];
OneSignal.SetSubscription(false);
// RN SDK 4.x.x use
OneSignal.disablePush(true);
// RN SDK 3.x.x use
OneSignal.setSubscription(false);
window.plugins.OneSignal.setSubscription(false);
// Flutter SDK 3.x.x use
await OneSignal.shared.disablePush(true);
// Flutter SDK 2.x.x use
await OneSignal.shared.setSubscription(false);
OneSignal.SetSubscription(false);
OneSignal.SetSubscription(false)
OneSignal.setSubscription(false);
External User Ids
setExternalUserId
Method
setExternalUserId
MethodCall this method each time the user logs into your app/site to pass in your custom User ID (as a string).
String externalUserId = "123456789"; // You will supply the external user id to the OneSignal SDK
// Setting External User Id with Callback Available in SDK Version 4.0.0+
OneSignal.setExternalUserId(externalUserId, new OneSignal.OSExternalUserIdUpdateCompletionHandler() {
@Override
public void onSuccess(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());
try {
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);
}
} catch (JSONException e) {
e.printStackTrace();
}
try {
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);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(OneSignal.ExternalIdError error) {
// The results will contain push and email failure statuses
// Use this to detect if external_user_id was not set and retry when a better network connection is made
OneSignal.onesignalLog(OneSignal.LOG_LEVEL.VERBOSE, "Set external user id done with error: " + error.toString());
}
});
//------------------------------------------------------------------------
// 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 3.x.x
OneSignal.setExternalUserId(externalUserId, withSuccess: { 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)
}
})
//------------------------------------------------------------------------
// Setting External User Id with Callback Available in SDK Version 2.x.x
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
removeExternalUserId
MethodIf 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
setRequiresUserPrivacyConsent
MethodFor 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
setLocationShared
MethodDisable 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];
OneSignal.SetLocationShared(false);
OneSignal.setLocationShared(false);
window.plugins.OneSignal.setLocationShared(false)
await OneSignal.shared.setLocationShared(false);
OneSignal.SetLocationShared(false);
//Our Web SDK does not track location, you can setup the browser to track this and tag the user with the latitutde and longitude
isLocationShared
Method
isLocationShared
MethodReturn a boolean that indicates location shared state (defaults to true if your app has location permission).
boolean locationShared = OneSignal.isLocationShared();
let locationShared = OneSignal.isLocationShared()
BOOL locationShared = [OneSignal isLocationShared];
// Available in major release version
window.plugins.OneSignal.isLocationShared(function(shared) {
});
promptLocation
Method
promptLocation
MethodPrompts 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"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_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>
On Android, you need to add the location dependency
dependencies {
...
implementation 'com.google.android.gms:play-services-location:YOUR_PLAY_SERVICES_VERSION'
}
Finally, don't forget to call the prompt location method
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.
See Data Tag Implementation for more details.
Sending Notifications
postNotification
Method
postNotification
MethodAllows 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 astags
andincluded_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*, JSONString, Callback | 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);
});
}
const { userId } = await OneSignal.getDeviceState();
const notificationObj = {
contents: {en: "Message Body"},
include_player_ids: [userId]
};
const jsonString = JSON.stringify(notificationObj);
OneSignal.postNotification(jsonString, (success) => {
console.log("Success:", success);
}, (error) => {
console.log("Error:", error );
});
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
clearOneSignalNotifications
MethodAndroid only. 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
setEmail
MethodAllows you to set the user's email address with the OneSignal SDK. We offer several overloaded versions of this method. If the user changes their email, you need to call logoutEmail
and then setEmail
to update it.
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.
Example code see Email Quickstart.
OSEmailSubscriptionState
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
logoutEmail
MethodIf your app implements logout functionality, you can call logoutEmail
to dissociate the email from the device.
Example code see Email Quickstart.
addEmailSubscriptionObserver
Method
addEmailSubscriptionObserver
MethodTracks changes to email subscriptions (for example, if the user sets their email, or logs out). In order to subscribe to email subscription changes.
Example code see Email Quickstart.
SMS
setSMSNumber
Method
setSMSNumber
MethodAllows you to set the user's SMS number with the OneSignal SDK. We offer several overloaded versions of this method. If the user changes their SMS number, you need to call logoutSMSNumber
and then setSMSNumber
to update it.
Example code see SMS Quickstart.
If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an SMS authentication token and send it to your app.
Code examples can be found in Identity Verification
OSSMSSubscriptionObserver
OSSMSSubscriptionObserver
Checks the subscription state of the SMS number tied to the current device record. You can only use this if you added SMS number with the setSMSNumber
method.
Example code see SMS Quickstart.
logoutSMSNumber
Method
logoutSMSNumber
MethodIf your app implements logout functionality, you can call logoutSMSNumber
to dissociate the SMS number from the device.
Example code see SMS Quickstart.
addSMSSubscriptionObserver
Method
addSMSSubscriptionObserver
MethodTracks changes to SMS subscriptions (for example, if the user sets their SMS number, or logs out).
Example code see SMS Quickstart.
Now, whenever the SMS subscription changes, this method will be called:
OSSMSSubscriptionObserver subscriptionObserver = new OSSMSSubscriptionObserver() {
@Override
public void public void onSMSSubscriptionChanged(OSSMSSubscriptionStateChanges stateChanges) {
}
};
func onOSSMSSubscriptionChanged(_ stateChanges: OSSMSSubscriptionStateChanges!) {
}
-(void)onOSSMSSubscriptionChanged:(OSSMSSubscriptionStateChanges *)stateChanges {
}
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
addTrigger
MethodAdd 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
addTriggers
MethodAdd 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
removeTriggerForKey
MethodRemoves 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
removeTriggersForKeys
MethodRemoves 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
getTriggerValueForKey
MethodGets 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
pauseInAppMessages
MethodAllows 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
setInAppMessageClickHandler
MethodSets a In-App Message opened handler. The instance will be called when an In-App Message action is tapped on.
Parameter | Type | Description |
---|---|---|
handler | OSInAppMessageClickHandler - Android OSHandleInAppMessageActionClickBlock - iOS | Instance to a class implementing this interference. |
OneSignal.startInit(this)
.setInAppMessageClickHandler(new OSInAppMessageClickHandler())
.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
InAppMessageClickHandler
HandlerUse 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
OSInAppMessageAction
ClassDetails 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 pressedany action on the In-App Message. |
closesMessage | Boolean | Iftrue , the In App Message will animate off the screen. Iffalse , the In App Message will stay on screen until the user dismisses it. |
Updated over 1 year ago