Mobile SDK Reference

Mobile SDK API Reference

📘

You're Viewing User Model Documentation

OneSignal is in the process of migrating from a device-centric model (player ID) to a new user-centric data model (OneSignal ID). To learn more, check out the User Model Migration Guide.

Please refer to Version 9 of our documentation for device-centric information.

🚧

Targeting Android?

Use onesignal-android-sdk v5.1.7 or later or a compatible wrapper SDK which includes that version. Refer to release notes available on Github to learn which version of our Android SDK is included in a wrapper SDK.

Setup

These methods serve as a reference and are just a single step in the setup process. Make sure to follow the steps for your particular platform here:

initialize()

Initializes the OneSignal SDK. This should be called during application startup. The ONESIGNAL_APP_ID can be found in Keys & IDs.

OneSignal.initWithContext(this, ONESIGNAL_APP_ID);
OneSignal.initWithContext(this, ONESIGNAL_APP_ID)
#import <OneSignalFramework/OneSignalFramework.h>

[OneSignal initialize:@"YOUR_ONESIGNAL_APP_ID" withLaunchOptions:launchOptions];
import OneSignalFramework

OneSignal.initialize("YOUR_ONESIGNAL_APP_ID", withLaunchOptions: launchOptions)
OneSignal.Initialize("YOUR_ONESIGNAL_APP_ID");
OneSignal.initialize("YOUR_ONESIGNAL_APP_ID");
OneSignal.initialize("YOUR_ONESIGNAL_APP_ID");
window.plugins.OneSignal.initialize("YOUR_ONESIGNAL_APP_ID");

User

When Users access your app, OneSignal creates both a user-level ID called the OneSignal ID and a unique subscription-level ID called the Subscription ID. Users can have multiple Subscriptions depending on how many devices, email addresses and phone numbers they have in your app. You can identify and associate multiple subscriptions to a single user by logging them into OneSignal under your own unique user ID. The login method sets your user ID to be the OneSignal External ID and updates the OneSignal ID to be the same across all subscriptions with the same External ID.

login()

Log the user into OneSignal under your user identifier. This sets your user ID as the OneSignal external_id and switches the context to that specific user (onesignal_id). All subscriptions identified with the same external_id will have the same onesignal_id.

  • If the external_id exists, the user will be retrieved, and the onesignal_id will change to the previously identified version. Any data collected while the user was anonymous will not be applied to the now logged-in user, and the anonymous data will be lost.
  • If the external_id does not exist, the local state will be saved under the current onesignal_id. Any data collected while the user was anonymous will be kept.

The login method should be called whenever the user is identified in your app. The method has built-in retries when there is no network connection, or we receive a 500 response from the server.

  • Android will retry the login request every few seconds.
  • iOS will retry 4 times with backoff with these intervals 5 seconds -> 15 seconds -> 45 seconds -> 135 seconds. After which it will not retry anymore until the next session (app backgrounded for > 30 seconds or killed and restarted).

For example, if a user turned off the internet, called login, then killed the app, turned on the internet, and opened the app again. The external_id will be set on the user.

OneSignal.login("external_id");
OneSignal.login("external_id")
[OneSignal login:@"external_id"];
OneSignal.login("external_id")
OneSignal.Login("external_id");
OneSignal.login("external_id");
OneSignal.login("external_id");
window.plugins.OneSignal.login("external_id");

logout()

Log out the user previously logged in via the login method. This disassociates all user properties like the external_id, other custom aliases, and properties like tags. A new onesignal_id is associate with the device which now references a new anonymous user. An anonymous user has no user identity that can later be retrieved, except through this device, as long as the app remains installed and the app data is not cleared.

OneSignal.logout();
OneSignal.logout()
[OneSignal logout]
OneSignal.logout()
OneSignal.Logout();
OneSignal.logout();
OneSignal.logout();
window.plugins.OneSignal.logout();

getOnesignalId()

Get the user's current OneSignal ID. May be null if called too early. Its recommended to use the User State Observer method below as the OneSignal ID can change depending on when you call the login method.

String id = OneSignal.getUser().getOnesignalId();
val id = OneSignal.User.onesignalId
NSString* id = OneSignal.User.onesignalId
let id: String? = OneSignal.User.onesignalId
OneSignal.User.OneSignalId;
await OneSignal.User.getOnesignalId();
await OneSignal.User.getOnesignalId();
await window.plugins.OneSignal.User.getOnesignalId();

getExternalId()

Get the user's current External ID. May be null if called to early or not set via the login method yet. Its recommended to use the User State Observer method below as the user context can change depending on when you call the login method.

String id = OneSignal.getUser().getExternalId();
val id = OneSignal.User.externalId
NSString* id = OneSignal.User.externalId
let id: String? = OneSignal.User.externalId
OneSignal.User.ExternalId
await OneSignal.User.getExternalId();
await OneSignal.User.getExternalId();
await window.plugins.OneSignal.User.getExternalId();

addObserver() User State

The User name space is accessible via OneSignal.User and provides access to user-scoped functionality. Use the OSUserStateObserver.onUserStateDidChange method to detect when the user state changes, like after calling login. The User State contains the nullable onesignalId and externalId, and the observer will be fired when these values change.

// AppDelegate.h
// Add OSUserStateObserver after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSUserStateObserver>
@end

// AppDelegate.m
@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Add your AppDelegate as an observer
    [OneSignal.User addObserver:self];
}

// Add this new method
- (void)onUserStateDidChangeWithState:(OSUserChangedState * _Nonnull)state {
    // prints out all properties
    NSLog(@"OSUserChangedState:\n%@", [state jsonRepresentation]);
    NSLog(@"current externalId: %@", state.current.externalId);
    NSLog(@"current onesignalId: %@", state.current.onesignalId);
}
@end

// Remove the observer
[OneSignal.User removeObserver:self];
// AppDelegate.swift
// Add OSUserStateObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSUserStateObserver {

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

    // Add this new method
    func onUserStateDidChange(state: OSUserChangedState) {
        // prints out all properties
        print("OSUserChangedState: \n\(state.jsonRepresentation())")
        print(state.current.externalId)
        print(state.current.onesignalId)
    }
}

// Remove the observer
OneSignal.User.removeObserver(self)
OneSignal.User.Changed += _userStateChanged;

private void _userStateChanged(object sender, UserStateChangedEventArgs e) {
    ...
}
const listener = (event: UserChangedState) => {
    console.log("User changed: " + (event));
};

OneSignal.User.addEventListener("change", listener);
// Remove the listener
OneSignal.User.removeEventListener("change", listener);
OneSignal.User.addObserver((state) {
	var userState = state.jsonRepresentation();
    print('OneSignal user changed: $userState');
});

/// Remove a user state observer that has been previously added.
OneSignal.User.removeObserver(observer);
const listener = (event: UserChangedState) => {
    console.log("User changed: " + (event));
};
OneSignal.User.addEventListener("change", listener);
// Remove the listener
OneSignal.User.removeEventListener("change", listener);

addAlias()

Set an alias for the current user. If the alias label exists on this user, it will be overwritten.

Aliases added to subscriptions without external_id will not sync across multiple subscriptions because this method does not change the onesignal_id like the login method for existing users. It is recommended to add aliases after calling the login method which sets the external_id. See Aliases & External ID for more details.

OneSignal.getUser().addAlias("ALIAS_LABEL", "ALIAS_ID");
OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID")
[OneSignal.User addAliasWithLabel:@"ALIAS_LABEL" id:@"ALIAS_ID"];
OneSignal.User.addAlias(label: "ALIAS_LABEL", id: "ALIAS_ID")
OneSignal.User.AddAlias("ALIAS_LABEL", "ALIAS_ID");
OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");
OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");
window.plugins.OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");

addAliases()

Set aliases for the current user. If any alias labels exist on the user, they will be overwritten.

Aliases added to subscriptions without external_id will not sync across multiple subscriptions because this method does not change the onesignal_id like the login method for existing users. It is recommended to add aliases after calling the login method which sets the external_id. See Aliases & External ID for more details.

HashMap<String, String> aliases = new HashMap<String, String>();
aliases.put("ALIAS_LABEL_01", "ALIAS_ID_01");
aliases.put("ALIAS_LABEL_02", "ALIAS_ID_02");
OneSignal.getUser().addAliases(aliases);
var aliases = mapOf("ALIAS_LABEL_01" to "ALIAS_ID_01", "ALIAS_LABEL_02" to "ALIAS_ID_02")
OneSignal.User.addAliases(aliases)
[OneSignal.User addAliases:@{@"ALIAS_LABEL_01": @"ALIAS_ID_01", @"ALIAS_LABEL_02": @"ALIAS_ID_02"}]
OneSignal.User.addAliases(["ALIAS_LABEL_01": "ALIAS_ID_01", "ALIAS_LABEL_02": "ALIAS_ID_02"])
OneSignal.User.AddAliases(new Dictionary<string, string> { 
  { "ALIAS_LABEL_01", "ALIAS_ID_01" },
  { "ALIAS_LABEL_02", "ALIAS_ID_02" }
});
OneSignal.User.addAliases({ALIAS_LABEL_01: "ALIAS_ID_01", ALIAS_LABEL_02: "ALIAS_ID_02"});
var aliases = <String, String>{
  "alias_key_1": "alias_id_1",
  "alias_key_2": "alias_id_2"
};
OneSignal.User.addAliases(aliases);
window.plugins.OneSignal.User.addAliases({ALIAS_LABEL_01: "ALIAS_ID_01", ALIAS_LABEL_02: "ALIAS_ID_02"});

removeAlias()

Remove an alias from the current user.

OneSignal.getUser().removeAlias("ALIAS_LABEL")
OneSignal.User.removeAlias("ALIAS_LABEL")
[OneSignal.User removeAlias:@"ALIAS_LABEL"]
OneSignal.User.removeAlias("ALIAS_LABEL")
OneSignal.User.RemoveAlias("ALIAS_LABEL");
OneSignal.User.removeAlias("ALIAS_LABEL");
OneSignal.User.removeAlias("ALIAS_LABEL");
window.plugins.OneSignal.User.removeAlias("ALIAS_LABEL");

removeAliases()

Remove aliases from the current user.

HashSet<String> labels = new HashSet<String>();
labels.add("ALIAS_LABEL_01");
labels.add("ALIAS_LABEL_02");
OneSignal.getUser().removeAliases(labels);
OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]);
[OneSignal.User removeAliases:@[@"ALIAS_LABEL_01", @"ALIAS_LABEL_02"]]
OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"])
OneSignal.User.RemoveAliases(new[] { "ALIAS_LABEL_01", "ALIAS_LABEL_02" });
OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]);
var aliases = <String>["alias_key_1", "alias_key_2"];
OneSignal.User.removeAliases(aliases);
window.plugins.OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]);

Language

setLanguage()

The user's language property is set automatically by the OneSignal SDK based on the device settings when the subscription is created. You can override this by passing in the ISO 639-1 language code.

OneSignal.getUser().setLanguage("en");
OneSignal.User.setLanguage("en")
[OneSignal.User setLanguage:@"en"]
OneSignal.User.setLanguage("en")
OneSignal.User.Language = "en";
OneSignal.User.setLanguage("en");
OneSignal.User.setLanguage("en");
window.plugins.OneSignal.User.setLanguage("en");

Data Tags

Data Tags are custom key : value pairs of string or number data you set on users based on events or user data of your choosing. For example, you can tag a user based on which message they engaged with, so later, you can create Segments or further Personalize Messages. See Data Tags Overview for more details on use cases.

addTag()

Add a tag for the current user. If the tag key already exists, it will be replaced with the value provided here. If you try to set more tags on a user than you plan allows, it will fail. You will need to delete any unwanted tags first before setting or updating tags. See Tags FAQ for details.

OneSignal.getUser().addTag("KEY", "VALUE");

OneSignal.User.addTag("KEY", "VALUE")

OneSignal.User.addTag(key: "KEY", value: "VALUE")

[OneSignal.User addTag:@"KEY" value:@"VALUE"];

OneSignal.User.addTag("KEY", "VALUE");

OneSignal.User.AddTag("KEY", "VALUE");
OneSignal.User.addTag('my_tag', 'tag');
OneSignal.User.addTagWithKey("test1", "val1");
window.plugins.OneSignal.User.addTag("KEY", "VALUE");

addTags()

Add multiple tags for the current user. A tag key will be replaced with its corresponding value if it already exists. If you try to set more tags on a user than you plan allows, it will fail. You will need to delete any unwanted tags first before setting or updating tags. See Tags FAQ for details.

OneSignal.getUser().addTags(new HashMap<String, String>() {{
  put("KEY_01", "VALUE_01");
  put("KEY_02", "VALUE_02");
}});

OneSignal.User.addTags(mapOf("KEY_01" to "VALUE_01", "KEY_02" to "VALUE_02"))

[OneSignal.User addTags:@{@""KEY_01"": @""VALUE_01"", @""KEY_02"": @""VALUE_02""}];

OneSignal.User.addTags(["KEY_01": "VALUE_01", "KEY_02": "VALUE_02"])

const tags = { 
 KEY_01: "VALUE_01",
 KEY_02: "VALUE_02",
 KEY_03: "VALUE_03"
};
OneSignal.User.addTags(tags);

OneSignal.User.AddTags(new Dictionary<string, string> { 
  { "KEY_01", "VALUE_01" },
  { "KEY_02", "VALUE_02" }
});
OneSignal.User.addTags({my_tag1: 'my_value', my_tag2: 'my_value2'});
var tags = {'test': 'value', 'test2': 'value2'};
OneSignal.User.addTags(tags);
window.plugins.OneSignal.User.addTags({"KEY_01": "VALUE_01", "KEY_02": "VALUE_02"});

removeTag()

Remove the data tag with the provided key from the current user.

OneSignal.getUser().removeTag("KEY");
OneSignal.User.removeTag("KEY")

[OneSignal.User removeTag:@"KEY"];

OneSignal.User.removeTag("KEY")

OneSignal.User.removeTag("KEY");

OneSignal.User.RemoveTag("KEY");
OneSignal.User.removeTag('my_tag1');
OneSignal.User.removeTag("test");
window.plugins.OneSignal.User.removeTag("KEY");

removeTags()

Remove multiple tags from the current user.

OneSignal.getUser().removeTags(Arrays.asList("KEY_01", "KEY_02"));
OneSignal.User.removeTags(listOf("KEY_01", "KEY_02"))

[OneSignal.User removeTags:@[@""KEY_01"", @""KEY_02""]]

OneSignal.User.removeTags([""KEY_01"", ""KEY_02""])

const tags =  ['KEY_01', 'KEY_02', 'KEY_03'];
OneSignal.User.removeTags(tags);

OneSignal.User.RemoveTags(new string[] { "KEY_01", "KEY_02" });
OneSignal.User.removeTags(['my_tag1', 'my_tag2']);
OneSignal.User.removeTags(["test", "test2"])
window.plugins.OneSignal.User.removeTags(["KEY_01", "KEY_02"]);

getTags()

Requires SDK 5.0.5+

Loads the current user's local tags. Remote tags are pulled and stored locally when the user changes after calling login() or when a new session is started – your app is opened after more than 30 seconds of being out-of-focus.

Map<String, String> tags = OneSignal.getUser().getTags();

val tags: Map<String, String> = OneSignal.User.getTags()	

let tags = OneSignal.User.getTags()	

NSDictionary<NSString*, NSString*> *tags = [OneSignal.User getTags]	

const tags = OneSignal.User.getTags()

const getTags = async () => {
    const tags = await OneSignal.User.getTags();
    console.log('Tags:', tags);
};
const getTags = async () => {
    const tags = await window.plugins.OneSignal.User.getTags();
    console.log('Tags:', tags);
};

Privacy

setConsentRequired()

Determines whether users must consent to data collection before sending their data to OneSignal. This should be set to true to ensure compliance before invoking the init method.

OneSignal.setConsentRequired(true);
OneSignal.consentRequired = true
[OneSignal setConsentRequired:true];
OneSignal.setConsentRequired = true
OneSignal.ConsentRequired = true;
OneSignal.setConsentRequired(true);
OneSignal.consentRequired(true);
 window.plugins.OneSignal.setConsentRequired(true);

setConsentGiven()

Sets whether privacy consent has been granted. If setConsentRequired() is called with true, the SDK will not be fully enabled until this method is called with true. Calling methods like sendTags will result in a no-op until you explicitly inform the SDK the user has provided consent.

OneSignal.setConsentGiven(true);
OneSignal.consentGiven = true
[OneSignal setConsentGiven:true];
OneSignal.setConsentGiven(true)
OneSignal.ConsentGiven = true;
OneSignal.setConsentGiven(true);
OneSignal.consentGiven(true);
window.plugins.OneSignal.setConsentGiven(true);

Location

setIsLocationShared()

Location permissions enable geotagging in the OneSignal dashboard to send notifications to users based on their location. See Location-Triggered Notifications for more details.

Setting the property to false will disable location sharing.

// Enable location sharing
OneSignal.getLocation().setIsLocationShared(true);
// Enable location sharing
OneSignal.location.isLocationShared = true
// Enable location sharing
[OneSignal.Location setShared:true]
// Enable location sharing
OneSignal.Location.isShared = true
OneSignal.Location.IsShared = true;
OneSignal.Location.setShared(true);
OneSignal.Location.setShared(true);
window.plugins.OneSignal.Location.setShared(true);

isShared()

Whether the location is currently shared with OneSignal. Defaults to true if your app has location permission.

boolean isShared = OneSignal.Location.isShared();
var isShared: Boolean = OneSignal.isShared
BOOL locationShared = [OneSignal isLocationShared];
let locationShared = OneSignal.Location.isShared
bool isShared = OneSignal.Location.IsShared;
OneSignal.Location.isShared();
OneSignal.Location.isShared();
window.plugins.OneSignal.Location.isShared(isShared => {
  console.log("Location shared: ", isShared);
});

requestPermission()

Prompt the user for location permissions to allow geotagging. It is recommended to use soft-prompts with In-App Messages. See How to Prompt for Location Tracking.

OneSignal.getLocation().requestPermission(true, Continue.with((result) -> {

}));
OneSignal.location.requestPermission(true)
[OneSignal.Location requestPermission];
OneSignal.Location.requestPermission()
OneSignal.Location.RequestPermission();
OneSignal.Location.requestPermission();
OneSignal.Location.requestPermission();
window.plugins.OneSignal.Location.requestPermission();

Configure location on Android

  1. Add location permissions to your AndroidManifest.xml file.
// 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" />
  1. Add the location dependency.
dependencies {
  ...
  implementation 'com.google.android.gms:play-services-location:YOUR_PLAY_SERVICES_VERSION'
}

Configure location on iOS

Add location permissions to your app's info.plist file and ensure that your application includes the CoreLocation framework in its Frameworks, Libraries, and Embedded Content.

// 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>

Push Notifications

getPermission()

Determine whether the app has notification permission. Returns true when the app has permission to display notifications.

  • This is just the app's permission and doesn't factor in OneSignal's optOut status or the existence of the Subscription ID and Push Token, see OneSignal.User.PushSubscription for these.
OneSignal.getNotifications().getPermission();
OneSignal.Notifications.permission
[OneSignal.Notifications permission];
OneSignal.Notifications.permission
bool permission = OneSignal.Notifications.Permission;
await OneSignal.Notifications.getPermissionAsync();
var permission = OneSignal.Notifications.permission;
await window.plugins.OneSignal.Notifications.getPermissionAsync();

permissionNative (iOS)

Returns the enum for the native permission of the device. It will be one of:
0 = NotDetermined
1 = Denied
2 = Authorized
3 = Provisional (only available in iOS 12+)
4 = Ephemeral (only available in iOS 14+)

OSNotificationPermission permissionNative = [OneSignal.Notifications permissionNative]
let permissionNative: OSNotificationPermission = OneSignal.Notifications.permissionNative.rawValue
NotificationPermission PermissionNative
await OneSignal.Notifications.permissionNative()
var permissionNative = await OneSignal.Notifications.permissionNative()
await OneSignal.Notifications.permissionNative()

requestPermission()

iOS requires prompting users for permission to show push notifications that make sounds and "pop-ups" on the screen. iOS also supports Provisional Push Notifications delivered directly to the device's notification center.

Android 13+ requires prompting users for permission to show push notifications. This is a different behavior from previous Android versions. More details are in our Android 13 Push Notification Developer Update Guide.

You can display this prompt using the OneSignal SDK in 2 ways:

  1. Recommended: Use OneSignal's In-App Message Soft-Prompt before displaying the Native Alert. Details: Prompting for Push Permissions Guide.
  2. Programmatically Trigger the Native Alert Prompt with the OneSignal SDK requestPermission method.
// the `fallbackToSettings` arg is optional
OneSignal.getNotifications().requestPermission(Continue.with(r -> {
    if (r.isSuccess()) {
      if (r.getData()) {
        // `requestPermission` completed successfully and the user has accepted permission
      }
      else {
        // `requestPermission` completed successfully but the user has rejected permission
      }
    }
    else {
      // `requestPermission` completed unsuccessfully, check `r.getThrowable()` for more info on the failure reason
    }
}));
// the `fallbackToSettings` arg is optional
OneSignal.Notifications.requestPermission(true)
// the `fallbackToSettings` arg is optional
[OneSignal.Notifications requestPermission:^(BOOL accepted) {
  NSLog(@"User accepted notifications: %d", accepted);
} fallbackToSettings:true];
// the `fallbackToSettings` arg is optional
OneSignal.Notifications.requestPermission({ accepted in
  print("User accepted notifications: \(accepted)")
}, fallbackToSettings: true)
// the `fallbackToSettings` arg is optional
var result = await OneSignal.Notifications.RequestPermissionAsync(true);

if (result)
{
  // Notification permission was accepted.
}
else
{
  // Notification permission was denied.
}
OneSignal.Notifications.requestPermission(true);
OneSignal.Notifications.requestPermission(true);
OneSignal.Notifications.requestPermission(true).then((accepted: boolean) => {
    console.log("User accepted notifications: " + accepted);
});

Parameters

  • fallbackToSettings- option to display a prompt informing your users to re-enable notifications for the app after they've denied permissions when showing a push prompt is disallowed.

getCanRequestPermission()

Determine whether attempting to request notification permission will result in a prompt being displayed to the user. Returns true if the device has never been prompted for push notification permission.

boolean canRequest = OneSignal.getNotifications().getCanRequestPermission();
val canRequest: Boolean = OneSignal.Notifications.canRequestPermission
BOOL canRequest = [OneSignal.Notifications canRequestPermission]
let canRequest: Bool = OneSignal.Notifications.canRequestPermission
bool canRequest = OneSignal.Notifications.CanRequestPermission;
const canRequest = OneSignal.Notification.canRequestPermission;
const granted = await OneSignal.Notifications.canRequestPermission();
console.log(`Can Request Permission: ${granted}`);
OneSignal.Notifications.canRequest();
window.plugins.OneSignal.Notifications.canRequestPermission(canRequest => {
  console.log("Can request permission", canRequest);
}); 

addPermissionObserver() Notifications

Allows you to respond when the notification permission changes.

#permissionChange

The onOSPermissionChanged event is fired when the notification permission setting changes, including:

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

An instance is given to your onOSPermissionChanged callback, which provides what the value was ("from") and what the value is now ("to").

Any object implementing the permission observer and/or the push subscription observer protocols can be added as an observer. You can call the associated remove observer functions to remove any existing listeners.

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

public class MainActivity extends Activity implements IPermissionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.getNotifications().addPermissionObserver(this);
  }

  @Override
  public void onNotificationPermissionChange(permission: Boolean) {
    if (permission) {
			// Respond to permission accepted
    }
  }
}

class MyObserver: IPermissionObserver {
    init {
        OneSignal.Notifications.addPermissionObserver(this)
    }

    override fun onNotificationPermissionChange(permission: Boolean) {
        if (permission) {
            // respond to permission accepted
        }
    }
}
// AppDelegate.h
// Add OSNotificationPermissionObserver after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSNotificationPermissionObserver>
@end

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

// Add this new method
- (void)onNotificationPermissionDidChange:(BOOL)permission {
   //respond to new state
}

@end
// AppDelegate.swift
// Add OSNotificationPermissionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSNotificationPermissionObserver {

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

   // Add this new method
   func onNotificationPermissionDidChange(_ permission: Bool) {
      // respond to new permission state
   }
}
OneSignal.Notifications.PermissionChanged += (sender, e) =>
  {
    if (e.Permission)
    {
      // User just accepted notifications or turned them back on!
    }
    else
    {
      // User just turned off notifications.
    }
  };
OneSignal.Notifications.addEventListener('permissionChange', (granted: boolean) => {
  console.log('OneSignal: permission changed:', granted);
});
OneSignal.Notifications.addPermissionObserver((state) {
	print("Has permission " + state.toString());
});
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
let myPermissionListener = function(granted) {
	console.log("Has permission: " + granted);
};
window.plugins.OneSignal.Notifications.addEventListener("permissionChange", myPermissionListener);

removePermissionObserver()

Remove a push permission handler that has been previously added.

OneSignal.getNotifications().removePermissionObserver(this);
OneSignal.Notifications.removePermissionObserver(this)
[OneSignal.Notifications removePermissionObserver:self];
OneSignal.Notifications.removePermissionObserver(self)
OneSignal.Notifications.removePermissionObserver(observer);
OneSignal.Notifications.removePermissionObserver(observer);
window.plugins.OneSignal.Notifications.removeEventListener("permissionChange", myPermissionListener);

addObserver() Push subscription

Allows you to respond when the push subscription changess.

#change

The onPushSubscriptionChange event is fired whenever the device's push subscription changes, including:

  • Getting a push token from Google or Apple
  • Getting a subscription ID from OneSignal
  • optedIn is manually changed
  • User disables or enables notification permissions

The changed state object is given to your listener, which provides what the value was ("previous") and what the value is now ("current").

You can call the associated remove observer functions to remove any existing listeners.

public class MainActivity extends Activity implements IPushSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.getUser().getPushSubscription().addObserver(this);
  }
  
  @Override
  public void onPushSubscriptionChange(@NonNull PushSubscriptionChangedState state) {
    // This method will be fired when a subscription property changes
    // respond to the state change
  }
}

// Remove the observer
OneSignal.getUser().getPushSubscription().removeObserver(this);
class MyObserver : IPushSubscriptionObserver {
    init {
        OneSignal.User.pushSubscription.addObserver(this)
    }
    
    // This method will be fired when a subscription property changes
    override fun onPushSubscriptionChange(state: PushSubscriptionChangedState) {
        val pushToken = state.current.token
        if (state.current.optedIn) {
            // Respond to user subscribed
        }
    }
}

// Remove the observer
OneSignal.User.pushSubscription.removeObserver(this)
// AppDelegate.swift
// Add OSPushSubscriptionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSPushSubscriptionObserver {

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

   // Add this new method, which will be fired when a subscription property changes
   func onPushSubscriptionDidChange(state: OSPushSubscriptionChangedState) {
       // respond to state change
   }
}

// Remove the observer
OneSignal.User.pushSubscription.removeObserver(self)
// AppDelegate.h
// Add OSPushSubscriptionObserver after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSPushSubscriptionObserver>
@end

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

// Add this new method, which will be fired when a subscription property changes
- (void)onPushSubscriptionDidChangeWithState:(OSPushSubscriptionChangedState *)state {
   // respond to new state
}

@end

// Remove the observer
[OneSignal.User.pushSubscription removeObserver:self];
OneSignal.User.PushSubscription.Changed += (sender, e) =>
  {
    if (e.State.Current.Id != e.State.Previous.Id)
    {
      // OneSignal Subscription id changed.
    }
  };
OneSignal.User.pushSubscription.addEventListener('change', (subscription) => {
  console.log('OneSignal: subscription changed:', subscription);
});

// Removes the previously added listener
OneSignal.User.pushSubscription.removeEventListener('change', myListener);
OneSignal.User.pushSubscription.addObserver((state) {
  if (state.current.optedIn) {
  	/// respond to new state
	}
});

// Removes the previously added observer
OneSignal.User.pushSubscription.removeObserver(myObserver);
const listener = (event: PushSubscriptionChangedState) => {
  console.log("Push subscription changed: " + (event));
};

// Add the listener
window.plugins.OneSignal.User.pushSubscription.addEventListener("change", listener);

// Remove the listener
window.plugins.OneSignal.User.pushSubscription.removeEventListener("change", listener);

addClickListener()

Specify what should occur whenever a user opens a notification.

OneSignal.getNotifications().addClickListener(event ->
{
   Log.v(Tag.LOG_TAG, "INotificationClickListener.onClick fired" +
           " with event: " + event);
});
val clickListener = object : INotificationClickListener {
    override fun onClick(event: INotificationClickEvent) {
        // respond to click
    }
}
OneSignal.Notifications.addClickListener(clickListener)
OneSignal.Notifications.removeClickListener(clickListener)	
// AppDelegate.h
// Add OSNotificationClickListener after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSNotificationClickListener>
@end

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

- (void)onClickNotification:(OSNotificationClickEvent * _Nonnull)event {
    NSLog(@"Dev App onClickNotification with event %@", [event jsonRepresentation]);
}
// AppDelegate.swift
// Add OSNotificationClickListener after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSNotificationClickListener {

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

    func onClick(event: OSNotificationClickEvent) {
        // Respond to notification click
    }
OneSignal.Notifications.Clicked += (sender, e) =>
  {
    // Access the notification with e.Notification and the click result with e.Result
  };
OneSignal.Notifications.addEventListener('click', (event) => {
  console.log('OneSignal: notification clicked:', event);
});
OneSignal.Notifications.addClickListener((event) {
  print('NOTIFICATION CLICK LISTENER CALLED WITH EVENT: $event');
});
let myClickListener = async function(event) {
  let notificationData = JSON.stringify(event);
};
window.plugins.OneSignal.Notifications.addEventListener("click", myClickListener);

addForegroundLifecycleListener()

Set a handler to run before displaying a notification while the app is in focus. Use this handler to read and change notification data or decide whether it should show.

OneSignal.getNotifications().addForegroundLifecycleListener(new INotificationLifecycleListener() {
	 @Override
    public void onWillDisplay(@NonNull INotificationWillDisplayEvent event) {
        Log.v(Tag.LOG_TAG, "INotificationLifecycleListener.onWillDisplay fired" +
                " with event: " + event);

        IDisplayableNotification notification = event.getNotification();
        JSONObject data = notification.getAdditionalData();

        //Prevent OneSignal from displaying the notification immediately on return.
        event.preventDefault();
        // Use notification.display() to display the notification after some async work
        Runnable r = () -> {
            try {
                // Do some work
            } catch (InterruptedException ignored) {
            }

            notification.display();
        };

        Thread t = new Thread(r);
        t.start();
    }
});
val lifecycleListener = object : INotificationLifecycleListener {
    override fun onWillDisplay(event: INotificationWillDisplayEvent) {
        // respond to event
    }
}
OneSignal.Notifications.addForegroundLifecycleListener(lifecycleListener)
OneSignal.Notifications.removeForegroundLifecycleListener(lifecycleListener)
// AppDelegate.swift
// Add OSNotificationLifecycleListener after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSNotificationLifecycleListener {

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

  func onWillDisplay(event: OSNotificationWillDisplayEvent) {
    event.preventDefault()
    // Do async work
    event.notification.display()
  }
// AppDelegate.h
// Add OSNotificationLifecycleListener after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSNotificationLifecycleListener>
@end

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

- (void)onWillDisplayNotification:(OSNotificationWillDisplayEvent *)event {
    [event preventDefault];
    // Do async work
    [event.notification display];

}
OneSignal.Notifications.ForegroundWillDisplay += (sender, e) =>
  {
    // Prevent OneSignal from displaying the notification immediately on return.
    e.PreventDefault();

    // Do some async work

    // Display the notification after some async work
    e.Notification.Display();
  };
OneSignal.Notifications.addEventListener('foregroundWillDisplay',(event) => {
  event.preventDefault();
  // some async work

  // Use display() to display the notification after some async work
  event.getNotification().display();
});
OneSignal.Notifications.addForegroundWillDisplayListener((event) {
  /// Display Notification, preventDefault to not display
  event.preventDefault();

	/// Do async work

  /// notification.display() to display after preventing default
  event.notification.display();
});
let myLifecyleListener = function(event) {
        /// Display Notification, preventDefault to not display
  event.preventDefault();

  // Use notification.display() to display the notification after some async work
  event.notification.display();
}
window.plugins.OneSignal.Notifications.addEventListener("foregroundWillDisplay", myLifecyleListener);

📘

When does a foreground handler run?

The foreground handler runs after the Service Extensions, which can be used to modify the notification before showing it.

removeNotification() (Android)

Cancel a single notification based on its Android notification ID.

Use instead of Android's android.app.NotificationManager.cancel. Otherwise, the notification will be restored when your app is restarted.

OneSignal.getNotifications().removeNotification(32432);
OneSignal.Notifications.removeNotification(32432)
OneSignal.Notifications.removeNotification(32432);
OneSignal.Notifications.removeNotification(32432);
window.plugins.OneSignal.Notifications.removeNotification(32432);

removeGroupedNotifications() (Android)

Cancel a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept. There is no android.app.NotificationManager equivalent.

OneSignal.getNotifications().removeGroupedNotifications("GROUP");
OneSignal.Notifications.removeGroupedNotifications("GROUP")
OneSignal.Notifications.removeGroupedNotifications("GROUP");
window.plugins.OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY");
OneSignal.Notifications.removeGroupedNotifications("GROUP_KEY");

clearAllNotifications()

Removes all OneSignal notifications from the Notification Shade.

OneSignal.getNotifications.clearAllNotifications();
OneSignal.Notifications.clearAllNotifications()
[OneSignal.Notifications clearAll];
OneSignal.Notifications.clearAll()
OneSignal.Notifications.ClearAllNotifications();
OneSignal.Notifications.clearAll();
window.plugins.OneSignal.Notifications.clearAll();
OneSignal.Notifications.clearAll();

Use instead of Android's android.app.NotificationManager.cancel. Otherwise, the notifications will be restored when your app is restarted.


Push Subscription

id

The user's push subscription ID. See Subscriptions for more details.

May return null if called too early. Its recommended to get this data within the push permission observer and/or subscription observer to react to changes.

String id = OneSignal.getUser().getPushSubscription().getId();
val id = OneSignal.User.pushSubscription.id
NSString* id = OneSignal.User.pushSubscription.id
let id: String? = OneSignal.User.pushSubscription.id
OneSignal.User.PushSubscription.Id;
await OneSignal.User.pushSubscription.getIdAsync();
OneSignal.User.pushSubscription.id;
await window.plugins.OneSignal.User.pushSubscription.getIdAsync();

token

The subscription's push token. Required to receive push notifications.

May return null if called too early. Its recommended to get this data within the push permission observer and/or subscription observer to react to changes.

String pushToken = OneSignal.getUser().getPushSubscription().getToken();
val pushToken = OneSignal.User.subscriptions.push.token
NSString* token = OneSignal.User.pushSubscription.token
let token: String? = OneSignal.User.pushSubscription.token
OneSignal.User.PushSubscription.Token;
await OneSignal.User.pushSubscription.getTokenAsync();
OneSignal.User.pushSubscription.token;
await window.plugins.OneSignal.User.pushSubscription.getTokenAsync();

optOut()

Changes the subscription status of an opted-in push subscription to opted-out. The push subscription cannot get push notifications anymore until optIn() is called or use Update subscription API with enabled: true.

This method does not remove or invalidate push tokens. It is designed for sites that wish to have more granular control of which users receive notifications, such as when implementing notification preference pages.

The user's push subscription can only be opted-out if OneSignal.Notifications.permission is true.

OneSignal.getUser().getPushSubscription().optOut();
OneSignal.User.pushSubscription.optOut()
[OneSignal.User.pushSubscription optOut];
OneSignal.User.pushSubscription.optOut()
OneSignal.User.PushSubscription.OptOut();
OneSignal.User.pushSubscription.optOut();
OneSignal.User.pushSubscription.optOut();
window.plugins.OneSignal.User.pushSubscription.optOut();

optIn()

optIn() will display the native push notification permission prompt if the push subscription has never been asked for permission before. If the push subscription has already been prompted and the app’s settings has notification permission disabled, a native prompt will appear directing the user to the settings app to change the notification permission like this:

To prevent this behavior, remove the optIn method and use requestPermission method instead with the fallbackToSettings property set to false.

If you previously called the optOut() method, this changes the subscription status to opted-in. If the push token on the subscription is valid, the user should be able to get push notifications again.

This method does not trigger the website prompts and does not set or validate push tokens. It is designed for sites that wish to have more granular control of which users receive notifications, such as when implementing notification preference pages.

The user's push subscription can only be changed back to opted-in if both conditions are met:

  1. OneSignal.Notifications.permission is true.
  2. the optOut() method was previously used.
OneSignal.getUser().getPushSubscription().optIn();
OneSignal.User.pushSubscription.optIn()
[OneSignal.User.pushSubscription optIn];
OneSignal.User.pushSubscription.optIn()
OneSignal.User.PushSubscription.OptIn();
OneSignal.User.pushSubscription.optIn();
OneSignal.User.pushSubscription.optIn();
window.plugins.OneSignal.User.pushSubscription.optIn();

optedIn

Check if the user has allowed push notifications based on app and device permissions. It returns true if permissions are given and optOut hasn't been called. However, it doesn't verify the subscription and push token, which could result in the user not receiving notifications even if it returns true. Call this function within the callback of a push permission observer or subscription observer to ensure the value exists.

Boolean optedIn = OneSignal.getUser().getPushSubscription().getOptedIn();
val optedIn = OneSignal.User.subscriptions.push.optedIn
bool optedIn = OneSignal.User.pushSubscription.optedIn
let optedIn: Bool = OneSignal.User.pushSubscription.optedIn
OneSignal.User.PushSubscription.OptedIn;
await OneSignal.User.pushSubscription.getOptedInAsync();
OneSignal.User.pushSubscription.optedIn;
await OneSignal.User.pushSubscription.getOptedInAsync();

Outcomes

Track actions taken by users and attribute them to messages. See Outcomes for more details.

addOutcome()

Add an outcome with the provided name, captured against the current session.

OneSignal.getSession().addOutcome("OUTCOME_NAME");
OneSignal.Session.addOutcome("OUTCOME_NAME")
[OneSignal.Session addOutcome:@"OUTCOME_NAME"];
OneSignal.Session.addOutcome("OUTCOME_NAME")
OneSignal.Session.AddOutcome("OUTCOME_NAME");
OneSignal.Session.addOutcome("OUTCOME_NAME");
OneSignal.Session.addOutcome("normal_1");
window.plugins.OneSignal.Session.addOutcome("OUTCOME_NAME");

addUniqueOutcome()

Add a unique outcome with the provided name, captured against the current session.

OneSignal.getSession().addUniqueOutcome("OUTCOME_NAME");
OneSignal.Session.addUniqueOutcome("OUTCOME_NAME")
[OneSignal.Session addUniqueOutcome:@"OUTCOME_NAME"];
OneSignal.Session.addUniqueOutcome("OUTCOME_NAME")
OneSignal.Session.AddUniqueOutcome("OUTCOME_NAME");
OneSignal.Session.addUniqueOutcome("OUTCOME_NAME");
OneSignal.Session.addUniqueOutcome("unique_1");
window.plugins.OneSignal.Session.addUniqueOutcome("OUTCOME_NAME");

addOutcomeWithValue()

Add an outcome with the provided name and value captured against the current session.

OneSignal.getSession().addOutcomeWithValue("OUTCOME_NAME", 3.14);
OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 3.14)
[OneSignal.Session addOutcomeWithValue:@"OUTCOME_NAME" value: 3.14];
OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 3.14)
OneSignal.Session.AddOutcomeWithValue("OUTCOME_NAME", 3.14);
OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 1);
OneSignal.Session.addOutcomeWithValue("value_1", 3.2);
window.plugins.OneSignal.Session.addOutcomeWithValue("OUTCOME_NAME", 1);

In-App Messages

In-app messages do not require any code; however, the SDK enables you to customize when messages are presented and handle IAM lifecycle events. Triggers, which are created within the OneSignal Dashboard, determine whether a specific IAM should be presented to the user. See Triggers. Whenever a trigger is added or removed, the SDK evaluates if an IAM should be displayed based on the conditions specified in the OneSignal Dashboard. Triggers get reset each time the app is closed, so make sure to set them again when starting your app if you need any of them to be persistent.

addTrigger()

Add a trigger for the current user. If the trigger key already exists, it will be replaced with the value provided.

OneSignal.getInAppMessages().addTrigger("KEY", "VALUE");

OneSignal.InAppMessages.addTrigger("KEY", "VALUE")

[OneSignal.InAppMessages addTrigger:@"KEY" withValue:@"VALUE"];

OneSignal.InAppMessages.addTrigger("KEY", "VALUE")

OneSignal.InAppMessages.AddTrigger("KEY", "VALUE");
OneSignal.InAppMessages.addTrigger("triggerKey", "triggerValue");
OneSignal.InAppMessages.addTrigger("trigger_1", "one");
window.plugins.OneSignal.InAppMessages.addTrigger("triggerKey", "triggerValue");

📘

Triggers are not persisted

Note that triggers are not persisted to the backend. They only exist on the local device and apply to the current user.

addTriggers()

Add multiple triggers for the current user. If any trigger key already exists, it will be replaced with the value provided here.

OneSignal.getInAppMessages()
  .addTriggers(new HashMap<String, String>() {{
    put("KEY_01","VALUE_01");
    put("KEY_02", "VALUE_02");
  }});

OneSignal.InAppMessages.addTriggers(mapOf("KEY_01" to "VALUE_01", "KEY_02" to "VALUE_02"))

[OneSignal.InAppMessages addTriggers:@{@"KEY_01": @"VALUE_01", @"KEY_02": @"VALUE_02"}];

OneSignal.InAppMessages.addTriggers(["KEY_01": "VALUE_01", "KEY_02": "VALUE_02"])

OneSignal.InAppMessages.AddTriggers(new Dictionary<string, string> {
  { "KEY_01", "VALUE_01" },
  { "KEY_02", "VALUE_02" }
});
OneSignal.InAppMessages.addTriggers({"triggerKey1":"triggerValue", "triggerKey2":"triggerValue"});
Map<String, String> triggers = new Map<String, String>();
triggers["trigger_2"] = "two";
triggers["trigger_3"] = "three";
OneSignal.InAppMessages.addTriggers(triggers);
window.plugins.OneSignal.InAppMessages.addTriggers({"triggerKey1":"triggerValue", "triggerKey2":"triggerValue"});

removeTrigger()

Remove the trigger with the provided key from the current user.

OneSignal.getInAppMessages().removeTrigger("KEY");

OneSignal.InAppMessages.removeTrigger("KEY")

[OneSignal.InAppMessages removeTrigger:@"KEY"];

OneSignal.InAppMessages.removeTrigger("KEY")

OneSignal.InAppMessages.RemoveTrigger("KEY");
OneSignal.InAppMessages.removeTrigger("triggerKey");
OneSignal.InAppMessages.removeTrigger("trigger_1");
window.plugins.OneSignal.InAppMessages.removeTrigger("triggerKey");

removeTriggers()

Remove multiple triggers from the current user.

OneSignal.getInAppMessages().removeTriggers(Arrays.asList("KEY_01", "KEY_02"));
OneSignal.InAppMessages.removeTriggers(setOf("KEY_01", "KEY_02")

[OneSignal.InAppMessages removeTriggers:@[@"KEY_01", @"KEY_02"]];

OneSignal.InAppMessages.removeTriggers(["KEY_01", "KEY_02"])

OneSignal.InAppMessages.RemoveTriggers(new string[] { "KEY_01", "KEY_2" });
OneSignal.InAppMessages.removeTriggers(["triggerKey1", "triggerKey2"]);
List<String> triggerKeys = ["trigger_1", "trigger_3"];
OneSignal.InAppMessages.removeTriggers(triggerKeys);
window.plugins.OneSignal.InAppMessages.removeTriggers(["triggerKey1", "triggerKey2"]);

clearTriggers()

Clear all triggers from the current user.

OneSignal.getInAppMessages().clearTriggers();

OneSignal.InAppMessages.clearTriggers()

[OneSignal.InAppMessages clearTriggers];

OneSignal.InAppMessages.clearTriggers()

OneSignal.InAppMessages.ClearTriggers();
OneSignal.InAppMessages.clearTriggers();
OneSignal.InAppMessages.clearTriggers();
window.plugins.OneSignal.InAppMessages.clearTriggers();

paused

Set whether in-app messaging is currently paused. When set to true, no In-App messages will be presented to the user regardless of whether they qualify for them. When set to false, any messages the user qualifies for will be presented to them at the appropriate time.

OneSignal.getInAppMessages().setPaused(true);
OneSignal.InAppMessages.paused = true
[OneSignal.InAppMessages paused:true];

// Get `paused` state
BOOL paused = [OneSignal.InAppMessages paused];
OneSignal.InAppMessages.paused = true

// Get `paused` state
let paused = OneSignal.InAppMessages.paused
OneSignal.InAppMessages.Paused = true;
OneSignal.InAppMessages.setPaused(true);
OneSignal.InAppMessages.paused(true);
window.plugins.OneSignal.InAppMessages.setPaused(true);

addLifecycleListener()

Use the InAppMessageLifecycleListener methods to respond to In-App Messages being displayed and dismissed.

OneSignal.getInAppMessages().addLifecycleListener(new IInAppMessageLifecycleListener() {
    @Override
    public void onWillDisplay(@NonNull IInAppMessageWillDisplayEvent event) {
        Log.v(Tag.LOG_TAG, "onWillDisplayInAppMessage");
    }

    @Override
    public void onDidDisplay(@NonNull IInAppMessageDidDisplayEvent event) {
        Log.v(Tag.LOG_TAG, "onDidDisplayInAppMessage");
    }

    @Override
    public void onWillDismiss(@NonNull IInAppMessageWillDismissEvent event) {
        Log.v(Tag.LOG_TAG, "onWillDismissInAppMessage");
    }

    @Override
    public void onDidDismiss(@NonNull IInAppMessageDidDismissEvent event) {
        Log.v(Tag.LOG_TAG, "onDidDismissInAppMessage");
    }
});

val lifecycleListener = object : IInAppMessageLifecycleListener {
    override fun onWillDisplay(event: IInAppMessageWillDisplayEvent) {
        print(event.message.messageId)
    }

    override fun onDidDisplay(event: IInAppMessageDidDisplayEvent) {
        print(event.message.messageId)
    }

    override fun onWillDismiss(event: IInAppMessageWillDismissEvent) {
        print(event.message.messageId)
    }

    override fun onDidDismiss(event: IInAppMessageDidDismissEvent) {
        print(event.message.messageId)
    }
}
OneSignal.InAppMessages.addLifecycleListener(lifecycleListener)
OneSignal.InAppMessages.removeLifecycleListener(lifecycleListener)

// AppDelegate.h
// Add OSInAppMessageLifecycleListener as an implemented protocol of the class that will handle the In-App Message lifecycle events.
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSInAppMessageLifecycleListener>
@end

// AppDelegate.m
@implementation AppDelegate
  
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Add your implementing class as the listener.  
    [OneSignal.InAppMessages addLifecycleListener:self];
}

// Add one or more of the following optional lifecycle methods
- (void)onWillDisplayInAppMessage:(OSInAppMessageWillDisplayEvent *)event {
  NSLog(@"OSInAppMessageLifecycleListener: onWillDisplay Message: %@", event.message.messageId);
}

- (void)onDidDisplayInAppMessage:(OSInAppMessageDidDisplayEvent *)event {
  NSLog(@"OSInAppMessageLifecycleListener: onDidDisplay Message: %@", event.message.messageId);
}

- (void)onWillDismissInAppMessage:(OSInAppMessageWillDismissEvent *)event {
  NSLog(@"OSInAppMessageLifecycleListener: onWillDismiss Message: %@", event.message.messageId);
}

- (void)onDidDismissInAppMessage:(OSInAppMessageDidDismissEvent *)event {
  NSLog(@"OSInAppMessageLifecycleListener: onDidDismiss Message: %@", event.message.messageId);
}

// AppDelegate.swift
// Add OSInAppMessageLifecycleListener as an implemented protocol of the class that will handle the In-App Message lifecycle events.
class AppDelegate: UIResponder, UIApplicationDelegate, OSInAppMessageLifecycleListener {

  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Add your implementing class as the listener
    OneSignal.InAppMessages.addLifecycleListener(self)
  }

  // Add one or more of the following optional lifecycle methods

  func onWillDisplay(event: OSInAppMessageWillDisplayEvent) {
    print("OSInAppMessageLifecycleListener: onWillDisplay Message: \(event.message.messageId)")
  }
  func onDidDisplay(event: OSInAppMessageDidDisplayEvent) {
    print("OSInAppMessageLifecycleListener: onDidDisplay Message: \(event.message.messageId)")
  }
  func onWillDismiss(event: OSInAppMessageWillDismissEvent) {
    print("OSInAppMessageLifecycleListener: onWillDismiss Message: \(event.message.messageId)")
  }
  func onDidDisplay(event: OSInAppMessageDidDisplayEvent) {
    print("OSInAppMessageLifecycleListener: onDidDismiss Message: \(event.message.messageId)")
	}
}

OneSignal.InAppMessages.WillDisplay += (sender, e) =>
  {
    // Access the in-app message with e.Message
  };

OneSignal.InAppMessages.DidDisplay += (sender, e) =>
  {
    // Access the in-app message with e.Message
  };

OneSignal.InAppMessages.WillDismiss += (sender, e) =>
  {
    // Access the in-app message with e.Message
  };

OneSignal.InAppMessages.DidDismiss += (sender, e) =>
  {
    // Access the in-app message with e.Message
  };
OneSignal.InAppMessages.addEventListener('willDisplay', (event) => {
  console.log('OneSignal: will display IAM: ', event);
});

OneSignal.InAppMessages.addEventListener('didDisplay', (event) => {
  console.log('OneSignal: did display IAM: ', event);
});

OneSignal.InAppMessages.addEventListener('willDismiss', (event) => {
  console.log('OneSignal: will dismiss IAM: ', event);
});

OneSignal.InAppMessages.addEventListener('didDismiss', (event) => {
  console.log('OneSignal: did dismiss IAM: ', event);
});
OneSignal.InAppMessages.addWillDisplayListener((event) {
	print("ON WILL DISPLAY IN APP MESSAGE ${event.message.messageId}");
});
OneSignal.InAppMessages.addDidDisplayListener((event) {
	print("ON DID DISPLAY IN APP MESSAGE ${event.message.messageId}");
});
OneSignal.InAppMessages.addWillDismissListener((event) {
	print("ON WILL DISMISS IN APP MESSAGE ${event.message.messageId}");
});
OneSignal.InAppMessages.addDidDismissListener((event) {
	print("ON DID DISMISS IN APP MESSAGE ${event.message.messageId}");
});
// Define the lifecycle listener functions
let willDisplayListener = async function(event) {
  console.log("OneSignal: will display IAM: "+ event.messageId);
};
let didDisplayListener = async function(event) {
  console.log("OneSignal: did display IAM: "+ event.messageId);
};
let willDismissListener = async function(event) {
  console.log("OneSignal: will dismiss IAM: "+ event.messageId);
};
let didDismissListener = async function(event) {
  console.log("OneSignal: did dismiss IAM: "+ event.messageId);
};

// Listeners for each event added separately
window.plugins.OneSignal.InAppMessages.addEventListener("willDisplay", willDisplayListener);
window.plugins.OneSignal.InAppMessages.addEventListener("didDisplay", didDisplayListener);
window.plugins.OneSignal.InAppMessages.addEventListener("willDismiss", willDismissListener);
window.plugins.OneSignal.InAppMessages.addEventListener("didDismiss", didDismissListener);

addClickListener()

To respond to In App Message click events add a click listener. The event contains the message that was clicked and its metadata.

  • actionId: The identifier corresponding to the element clicked.
  • urlTarget: An enum specifying how the launch URL for the message will be presented.
  • url: The launch URL for the action, if any.
  • closingMessage: A boolean value indicating if the action resulted in the message being closed.
OneSignal.getInAppMessages().addClickListener(new IInAppMessageClickListener() {
    @Override
    public void onClick(@Nullable IInAppMessageClickEvent event) {
        Log.v(Tag.LOG_TAG, "INotificationClickListener.inAppMessageClicked");
    }
});
val clickListener = object : IInAppMessageClickListener {
    override fun onClick(event: IInAppMessageClickEvent) {
        print(event.result.actionId)
    }
}
OneSignal.InAppMessages.addClickListener(clickListener)

// Add this method to object implementing the OSInAppMessageClickListener protocol
- (void)onClickInAppMessage:(OSInAppMessageClickEvent * _Nonnull)event {
    NSLog(@"onClickInAppMessage event: %@", [event jsonRepresentation]);
    NSString *message = [NSString stringWithFormat:@"In App Message Click Occurred: messageId: %@ actionId: %@ url: %@ urlTarget: %@ closingMessage: %i",
                        event.message.messageId,
                        event.result.actionId,
                        event.result.url,
                        @(event.result.urlTarget),
                        event.result.closingMessage];
}

// Add your object as a listener
[OneSignal.InAppMessages addClickListener:self];

class MyInAppMessageClickListener : NSObject, OSInAppMessageClickListener {
    func onClick(event: OSInAppMessageClickEvent) {
        let messageId = event.message.messageId
        let result: OSInAppMessageClickResult = event.result
        let actionId = result.actionId
        let url = result.url
        let urlTarget: OSInAppMessageActionUrlType = result.urlTarget
        let closingMessage = result.closingMessage
    }
}

// Add your object as a listener
let myListener = MyInAppMessageClickListener()
OneSignal.InAppMessages.addClickListener(myListener)

OneSignal.InAppMessages.Clicked += (sender, e) =>
  {
    // Access the in-app message with e.Message and the click result with e.Result
  };
OneSignal.InAppMessages.addEventListener('click', (event) => {
  console.log('OneSignal IAM clicked:', event);
});
OneSignal.InAppMessages.addClickListener((event) {
	print("In App Message Clicked: \n${event.result.jsonRepresentation().replaceAll("\\n", "\n")}");
});
let inAppClickListener = async function(event) {
  let clickData = JSON.stringify(event);
  console.log("In-App Message Clicked: "+ clickData);
};
window.plugins.OneSignal.InAppMessages.addEventListener("click", inAppClickListener);

Email

addEmail()

Add a new email subscription to the current user.

OneSignal.getUser().addEmail("[email protected]")
OneSignal.User.addEmail("[email protected]")
[OneSignal.User addEmail:@"[email protected]"];
OneSignal.User.addEmail("[email protected]")
OneSignal.User.addEmail("[email protected]");
OneSignal.User.AddEmail("[email protected]");
OneSignal.User.addEmail("[email protected]");
OneSignal.User.addEmail("[email protected]");
window.plugins.OneSignal.User.addEmail("[email protected]");

📘

Use Identity Verification

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.

removeEmail()

Remove an email subscription from the current user. Returns false if the given email doesn't exist on the user within the SDK, no request will be made.

OneSignal.getUser().removeEmail("[email protected]")
OneSignal.User.removeEmail("[email protected]")
OneSignal.User.removeEmail("[email protected]")
[OneSignal.User removeEmail:@"[email protected]"];
OneSignal.User.removeEmail("[email protected]");
OneSignal.User.RemoveEmail("[email protected]");
OneSignal.User.removeEmail("[email protected]");
OneSignal.User.removeEmail("[email protected]");
window.plugins.OneSignal.User.removeEmail("[email protected]");

SMS

addSms()

Add a new SMS subscription (phone number) to the current user. Requires phone numbers to follow the E.164 international telephone number plan.

OneSignal.getUser().addSms("+15558675309")
OneSignal.User.addSms("+15558675309")
[OneSignal.User addSms:@"+15558675309"];
OneSignal.User.addSms("+15558675309")
OneSignal.User.AddSms("+15558675309");
OneSignal.User.addSms("+15558675309");
OneSignal.User.addSms("+15558675309");
OneSignal.User.addSms("+15558675309");
window.plugins.OneSignal.User.addSms("+15558675309");

📘

Use Identity Verification

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 or website.

removeSms()

Remove an SMS subscription (phone number) from the current user.

OneSignal.getUser().removeSms("+15558675309")
OneSignal.User.removeSms("+15558675309")
[OneSignal.User removeSms:@"+15558675309"];
OneSignal.User.removeSms("+15558675309")
OneSignal.User.RemoveSms("+15558675309");
OneSignal.User.removeSms("+15558675309");
OneSignal.User.removeSms("+15558675309");
OneSignal.User.removeSms("+15558675309");
window.plugins.OneSignal.User.removeSms("+15558675309");

Live Activity

Applications should allow users to opt-in to Live Activities. For example, your app gives the user the option to start the Live Activity within your US using a button or presenting an IAM. You may start and update a Live Activity via any method without an explicit prompt, unlike Notification Permission or Location Permission. Live Activities appear with the iOS Provisional Authorization UI. Live Activities must be started when your application is in the foreground. We recommend reading Apple’s developer guidelines to learn more about Live Activities.

enter()

Entering a Live Activity associates an activityId with a Live Activity Temporary Push Token on our server. Specify this identifier when using the Update Live Activities REST API to update one or multiple Live Activities simultaneously.

// ... your app's code 
let activity = try Activity<OneSignalWidgetAttributes>.request(
  attributes: attributes,
  contentState: contentState,
  pushType: .token)
Task {
    for await data in activity.pushTokenUpdates {
        let myToken = data.map {String(format: "%02x", $0)}.joined()
        // ... required code for entering a live activity
        // Activity ID cannot contain "/" characters
        OneSignal.LiveActivities.enter("my_activity_id", withToken: myToken)
    }
}
OneSignal.LiveActivities.enter("my_activity_id", token, (result: object) => {
    loggingFunction("enterLiveActivity completed with result: ", JSON.stringify(result));
})
OneSignal.LiveActivities.enterLiveActivity("my_activity_id", token).then((result) {
    print("Successfully enter live activity");
}).catchError((error) {
    print("Failed to enter live activity with error: $error");
});
var result = OneSignalSDK.DotNet.OneSignal.Default.EnterLiveActivity("my_activity_id", token);
if(result) {
    Console.WriteLine("Success");
}
var result = OneSignalSDK.Xamarin.OneSignal.Default.EnterLiveActivity("my_activity_id", token);
if(result) {
    Console.WriteLine("Success");
}
OneSignal.LiveActivities.EnterAsync("my_activity_id", token);
window.plugins.OneSignal.LiveActivities.enter("ACTIVITY_ID", "TOKEN", (result) => {
  console.log("Results of entering live activity: ", result);
});
OneSignal.LiveActivities.enter('ACTIVITY_ID', 'TOKEN', (result) => {
  console.log('Results of entering live activity: ', result);
});

exit()

Exiting a Live activity deletes the association between an Activity Identifier with the Live Activity push token on our server.

OneSignal.LiveActivities.exit("my_activity_id")
OneSignal.LiveActivities.exit("my_activity_id", (result: object) => {
    loggingFunction("exitLiveActivity completed with result: ", JSON.stringify(result));
})
OneSignal.LiveActivities.exit("your_activity_id").then((result) {
    print("Successfully exit live activity");
}).catchError((error) {
    print("Failed to exit live activity: $error");
});
OneSignalSDK.DotNet.OneSignal.Default.ExitLiveActivity("my_activity_id");
OneSignalSDK.DotNet.OneSignal.Default.ExitLiveActivity("my_activity_id");
OneSignal.LiveActivities.ExitAsync("my_activity_id");
window.plugins.OneSignal.LiveActivities.exit("ACTIVITY_ID", (result) => {
  console.log("Results of exiting live activity: ", result);
});
OneSignal.LiveActivities.exit('ACTIVITY_ID', (result) => {
  console.log('Results of exiting live activity: ', result);
});

Debugging

Enable logging to help debug if you run into an issue setting up OneSignal. This selector is static, call it before initializing OneSignal. For more details, see Getting a Debug Log. For websites, see Debugging with Browser Tools.

setLogLevel()

Set the logging level to print logs Android LogCat or Xcode logs.

// LogLevel: NONE | FATAL | ERROR | WARN | INFO | DEBUG | VERBOSE
OneSignal.getDebug().setLogLevel(OneSignal.LOG_LEVEL.VERBOSE);
// LogLevel: .None | .Fatal | .Error | .Warn | .Info | .Debug | .Verbose
OneSignal.Debug.logLevel = LogLevel.Verbose
// LogLevel: 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.Debug setLogLevel:ONE_S_LL_VERBOSE];
// LogLevel: 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.Debug.setLogLevel(.LL_VERBOSE)
// LogLevel: None | Fatal | Error | Warn | Info | Debug | Verbose
OneSignal.Debug.LogLevel = LogLevel.Verbose;
OneSignal.Debug.setLogLevel(LogLevel.Verbose);
OneSignal.Debug.setLogLevel(OSLogLevel.error);
// 0 = None, 1 = Fatal, 2 = Errors, 3 = Warnings, 4 = Info, 5 = Debug, 6 = Verbose
window.plugins.OneSignal.Debug.setLogLevel(6);

setAlertLevel()

Sets the logging level to show as alert dialogs in your app. Make sure to remove this before submitting to the app store.

OneSignal.getDebug.setAlertLevel(LogLevel.Exception);
OneSignal.Debug.alertLevel = LogLevel.Exception
[OneSignal.Debug setAlertLevel:ONE_S_LL_NONE];
OneSignal.Debug.setAlertLevel(.LL_NONE)
// LogLevel: None | Fatal | Error | Warn | Info | Debug | Verbose
OneSignal.Debug.AlertLevel = LogLevel.None;
OneSignal.Debug.setAlertLevel(LogLevel.Verbose);
OneSignal.Debug.setAlertLevel(OSLogLevel.none);
// 0 = None, 1 = Fatal, 2 = Errors, 3 = Warnings, 4 = Info, 5 = Debug, 6 = Verbose
window.plugins.OneSignal.Debug.setAlertLevel(0);