Comprehensive API reference for the OneSignal Mobile SDK, including initialization, user identity, subscriptions, tags, permissions, in-app messages, live activities, and more. Supports Android, iOS, Unity, React Native, Flutter, and Cordova/Ionic platforms.
Set the logging to print additional logs to Android LogCat or Xcode logs.
Call this before initializing OneSignal. See Getting a Debug Log for more details.
When users open your app, OneSignal automatically creates a OneSignal ID (user-level) and a Subscription ID (device-level). You can associate multiple subscriptions (e.g., devices, emails, phone numbers) with a single user by calling login() with your unique user identifier.
Sets the user context to the provided external_id. Ensures that all subscriptions and properties associated with this external_id are unified under a single onesignal_id. See Users for more details.Key behaviors:
If the external_id already exists, the SDK switches to that user. Anonymous data collected before login is not merged and will be discarded.
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.
SDK retries automatically on network failure or server error.
Call this method every time the user opens the app to make sure the External ID is set and the subscription is linked to the user.
Retrieve the current user’s OneSignal ID saved locally on the device. May be null if called before user state is initialized. Instead, use User State addObserver() to listen for user state changes.
val id = OneSignal.User.onesignalId
String id = OneSignal.getUser().getOnesignalId();
let id = OneSignal.User.onesignalId//Examplefunc getOneSignalId() async { if let id = OneSignal.User.onesignalId { print("OneSignal ID:", id) } else { print("OneSignal ID not available, try again.") }}
NSString* id = OneSignal.User.onesignalId
OneSignal.User.OneSignalId;
await OneSignal.User.getOnesignalId();//Exampleconst getOneSignalId = async () => { try { const id = await OneSignal.User.getOnesignalId(); console.log('OneSignal ID:', id); Alert.alert('OneSignal ID', id || 'No ID available'); } catch (error) { console.error('Error getting OneSignal ID:', error); Alert.alert('Error', 'Failed to get OneSignal ID'); }};
Retrieve the current user’s External ID saved locally on the device. May be null if not set via the login method or called before user state is initialized. Instead, use User State addObserver() to listen for user state changes.
val id = OneSignal.User.externalId
String id = OneSignal.getUser().getExternalId();
let id: String? = OneSignal.User.externalId
NSString* id = OneSignal.User.externalId
OneSignal.User.ExternalId
await OneSignal.User.getExternalId();//Exampleconst getExternalId = async () => { try { const id = await OneSignal.User.getExternalId(); console.log('External ID:', id); Alert.alert('External ID', id || 'No ID available'); } catch (error) { console.error('Error getting External ID:', error); Alert.alert('Error', 'Failed to get External ID'); }};
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);
// Add a single aliasOneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID")// Add multiple aliasesvar aliases = mapOf("ALIAS_LABEL_01" to "ALIAS_ID_01", "ALIAS_LABEL_02" to "ALIAS_ID_02")OneSignal.User.addAliases(aliases)// Remove a single aliasOneSignal.User.removeAlias("ALIAS_LABEL")// Remove multiple aliasesOneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"])
// Add a single aliasOneSignal.getUser().addAlias("ALIAS_LABEL", "ALIAS_ID");// Add multiple aliasesHashMap<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);// Remove a single aliasOneSignal.getUser().removeAlias("ALIAS_LABEL")// Remove multiple aliasesHashSet<String> labels = new HashSet<String>();labels.add("ALIAS_LABEL_01");labels.add("ALIAS_LABEL_02");OneSignal.getUser().removeAliases(labels);
// Add a single aliasOneSignal.User.addAlias(label: "ALIAS_LABEL", id: "ALIAS_ID")// Add multiple aliasesOneSignal.User.addAliases(["ALIAS_LABEL_01": "ALIAS_ID_01", "ALIAS_LABEL_02": "ALIAS_ID_02"])// Remove a single aliasOneSignal.User.removeAlias("ALIAS_LABEL")// Remove multiple aliasesOneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"])
// Add a single alias[OneSignal.User addAliasWithLabel:@"ALIAS_LABEL" id:@"ALIAS_ID"];// Add multiple aliases[OneSignal.User addAliases:@{@"ALIAS_LABEL_01": @"ALIAS_ID_01", @"ALIAS_LABEL_02": @"ALIAS_ID_02"}]// Remove a single alias[OneSignal.User removeAlias:@"ALIAS_LABEL"]// Remove multiple aliases[OneSignal.User removeAliases:@[@"ALIAS_LABEL_01", @"ALIAS_LABEL_02"]]
// Add a single aliasOneSignal.User.AddAlias("ALIAS_LABEL", "ALIAS_ID");// Add multiple aliasesOneSignal.User.AddAliases(new Dictionary<string, string> { { "ALIAS_LABEL_01", "ALIAS_ID_01" }, { "ALIAS_LABEL_02", "ALIAS_ID_02" }});// Remove a single aliasOneSignal.User.RemoveAlias("ALIAS_LABEL");// Remove multiple aliasesOneSignal.User.RemoveAliases(new[] {"ALIAS_LABEL_01", "ALIAS_LABEL_02"});
// Add a single aliasOneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");// Add multiple aliasesOneSignal.User.addAliases({ALIAS_LABEL_01: "ALIAS_ID_01", ALIAS_LABEL_02: "ALIAS_ID_02"});// Remove a single aliasOneSignal.User.removeAlias("ALIAS_LABEL");// Remove multiple aliasesOneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]);
// Add a single aliasOneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");// Add multiple aliasesvar aliases = <String, String>{ "alias_key_1": "alias_id_1", "alias_key_2": "alias_id_2"};OneSignal.User.addAliases(aliases);// Remove a single aliasOneSignal.User.removeAlias("ALIAS_LABEL");// Remove multiple aliasesvar aliases = <String>["alias_key_1", "alias_key_2"];OneSignal.User.removeAliases(aliases);
// Add a single alias - IonicOneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");// Add a single alias - Cordovawindow.plugins.OneSignal.User.addAlias("ALIAS_LABEL", "ALIAS_ID");// Add multiple aliases - IonicOneSignal.User.addAliases({ALIAS_LABEL_01: "ALIAS_ID_01", ALIAS_LABEL_02: "ALIAS_ID_02"});// Add multiple aliases - Cordovawindow.plugins.OneSignal.User.addAliases({ALIAS_LABEL_01: "ALIAS_ID_01", ALIAS_LABEL_02: "ALIAS_ID_02"});// Remove a single alias - IonicOneSignal.User.removeAlias("ALIAS_LABEL");// Remove a single alias - Cordovawindow.plugins.OneSignal.User.removeAlias("ALIAS_LABEL");// Remove multiple aliases - IonicOneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]);// Remove multiple aliases - Cordovawindow.plugins.OneSignal.User.removeAliases(["ALIAS_LABEL_01", "ALIAS_LABEL_02"]);
Suivez les actions des utilisateurs avec des propriétés associées. Voir Custom Events pour plus de détails.
Les événements personnalisés nécessitent les versions minimales suivantes du SDK : iOS 5.4.0, Android 5.6.1, React Native 5.3.0, Flutter 5.4.0, Unity 5.2.0.
Track and send a custom event performed by the current user.
name - Required. The name of the event as a string.
properties - Optional. Key-value pairs to add to the event. The properties dictionary or map must be serializable into a valid JSON Object. Supports nested values.
The SDK automatically includes app-specific data into the properties payload under the reserved key os_sdk that will be available to consume. For example, to target events by device type, you would access os_sdk.device_type.
// Track an event, by name, without additional propertiesOneSignal.User.trackEvent("my_event_name")// Track an event, by name, with additional propertiesOneSignal.User.trackEvent( name = "started_free_trial", properties = mapOf( "promo_code" to "NEW50", "membership_details" to mapOf( "vip" to true, "products_viewed_count" to 15 ) ))
// Track an event, by name, without additional propertiesOneSignal.getUser().trackEvent("my_event_name", null);// Track an event, by name, with additional propertiesMap<String, Object> membershipDetails = new HashMap<>();membershipDetails.put("vip", true);membershipDetails.put("products_viewed_count", 15);Map<String, Object> properties = new HashMap<>();properties.put("promo_code", "NEW50");properties.put("membership_details", membershipDetails);OneSignal.getUser().trackEvent("started_free_trial", properties);
// Track an event, by name, without additional propertiesOneSignal.User.trackEvent(name: "my_event_name", properties: nil)// Track an event, by name, with additional properties// The properties dictionary must be serializable into a valid JSON Object.let myProperties = [ "promo_code": "NEW50", "membership_details": [ "vip": true, "products_viewed_count": 15 ]]OneSignal.User.trackEvent(name: "started_free_trial", properties: myProperties)
// Track an event, by name, without additional properties[OneSignal.User trackEventWithName:@"my_event_name" properties:nil];// Track an event by name, with additional properties// The properties dictionary must be serializable into a valid JSON Object.NSDictionary *myProperties = @{ @"promo_code" : @"NEW50", @"membership_details" : @{ @"vip" : @true, @"products_viewed_count" : @15 } };[OneSignal.User trackEventWithName:@"started_free_trial" properties:myProperties];
// Track an event, by name, without additional propertiesOneSignal.User.TrackEvent("my_event_name")// Track an event, by name, with additional propertiesOneSignal.User.TrackEvent("started_free_trial", new Dictionary<string, object> { { "promo_code", "NEW50" }, { "membership_details", new Dictionary<string, object> { { "vip", true }, { "products_viewed_count", 15 } }}});
// Track an event, by name, without additional propertiesOneSignal.User.trackEvent("my_event_name")// Track an event, by name, with additional propertiesOneSignal.User.trackEvent("started_free_trial", { "promo_code": "NEW50", "membership_details": { "vip": true, "products_viewed_count": 15 }})
// Track an event, by name, without additional propertiesOneSignal.User.trackEvent("my_event_name")// Track an event, by name, with additional propertiesOneSignal.User.trackEvent("started_free_trial", { "promo_code": "NEW50", "membership_details": { "vip": true, "products_viewed_count": 15 }})
// Track an event, by name, without additional propertiesOneSignal.User.trackEvent("my_event_name")// Track an event, by name, with additional propertiesOneSignal.User.trackEvent("started_free_trial", { "promo_code": "NEW50", "membership_details": { "vip": true, "products_viewed_count": 15 }})
Grants or revokes user consent for data collection. Without consent, no data is sent to OneSignal and no subscription is created.
If setConsentRequired() is true, our SDK will not be fully enabled until setConsentGiven is called with true.
If setConsentGiven is set to true and a Subscription is created, then later it is set to false, that Subscription will no longer receive updates. The current data for that Subscription remains unchanged until setConsentGiven is set to true again.
LocationManager.startGetLocation: not possible, no location dependency found
Check your App’s dependencies. A common solutions is in you app/build.gradle add: implementation 'com.google.android.gms:play-services-location:21.0.1'
Enable your app to share location with OneSignal using the Location.setShared() method.
Request permission from the user for location tracking with the Location.requestPermission method or use in-app messages.
Use this method to allow our SDK to start tracking the Subscription’s latitude and longitude. Make sure you set the proper location permissions in your app first.
// Enable your app to share location with OneSignalOneSignal.Location.isShared = true// Returns true if your app is sharing location with OneSignalvar isShared: Boolean = OneSignal.isShared
// Enable your app to share location with OneSignalOneSignal.getLocation().setShared(true);// Returns true if your app is sharing location with OneSignalboolean isShared = OneSignal.Location.isShared();
// Enable your app to share location with OneSignalOneSignal.Location.isShared = true// Returns true if your app is sharing location with OneSignallet locationShared = OneSignal.Location.isShared
// Enable your app to share location with OneSignal[OneSignal.Location setShared:true]4// Returns true if your app is sharing location with OneSignalBOOL locationShared = [OneSignal isLocationShared];
// Enable your app to share location with OneSignalOneSignal.Location.IsShared = true;// Returns true if your app is sharing location with OneSignalbool isShared = OneSignal.Location.IsShared;
// Enable your app to share location with OneSignalOneSignal.Location.setShared(true);// Returns true if your app is sharing location with OneSignalOneSignal.Location.isShared();
// Enable your app to share location with OneSignalOneSignal.Location.setShared(true);// Returns true if your app is sharing location with OneSignalOneSignal.Location.isShared();
// Ionic// Enable your app to share location with OneSignalOneSignal.Location.setShared(true);// Returns true if your app is sharing location with OneSignalOneSignal.Location.isShared(isShared => { console.log("Location shared: ", isShared);});// Cordova// Enable your app to share location with OneSignalwindow.plugins.OneSignal.Location.setShared(true);// Returns true if your app is sharing location with OneSignalwindow.plugins.OneSignal.Location.isShared(isShared => {
Use this method to display the system-level location permission prompt to your users or instead use in-app messages. Make sure you set the proper location permissions in your app and enabled your app to share location with OneSignal.
Retrieve the current user’s push Subscription ID saved locally on the device. May return null if called too early. Its recommended to get this data within the subscription observer to react to changes.
val id = OneSignal.User.pushSubscription.id
String id = OneSignal.getUser().getPushSubscription().getId();
let id: String? = OneSignal.User.pushSubscription.id
NSString* id = OneSignal.User.pushSubscription.id
OneSignal.User.PushSubscription.Id;
await OneSignal.User.pushSubscription.getIdAsync();//Exampleconst getPushId = async () => { try { const id = await OneSignal.User.pushSubscription.getIdAsync(); console.log('Push Subscription ID:', id); Alert.alert('Push Subscription ID', id || 'No ID available'); } catch (error) { console.error('Error getting push ID:', error); Alert.alert('Error', 'Failed to get push subscription ID'); }};
Returns the current push subscription token. May return null if called too early. Its recommended to get this data within the subscription observer to react to changes.
val pushToken = OneSignal.User.pushSubscription.token
Use this method to respond to push subscription changes like:
The device receives a new push token from Google (FCM) or Apple (APNs)
OneSignal assigns a subscription ID
The optedIn value changes (e.g. called optIn() or optOut())
The user toggles push permission in system settings, then opens the app
When this happens, the SDK triggers the onPushSubscriptionChange event. Your listener receives a state object with the previous and current values so you can detect exactly what changed.To stop listening for updates, call the associated removeObserver() or removeEventListener() method.
class MyObserver : IPushSubscriptionObserver { init { OneSignal.User.pushSubscription.addObserver(this) } override fun onPushSubscriptionChange(state: PushSubscriptionChangedState) { if (state.current.optedIn) { println("User is now opted-in with push token: ${state.current.token}") } }}// Remove the observerOneSignal.User.pushSubscription.removeObserver(this)
//Add the IPushSubscriptionObserverpublic class MainActivity extends Activity implements IPushSubscriptionObserver { protected void onCreate(Bundle savedInstanceState) { //Add the addObserver method OneSignal.getUser().getPushSubscription().addObserver(this); } // This method will be fired when a subscription property changes @Override public void onPushSubscriptionChange(@NotNull PushSubscriptionChangedState pushSubscriptionChangedState) { //Example getting the subscription ID Log.i("OneSignal", "current subscription ID: " + pushSubscriptionChangedState.getCurrent().getId() ); }}// Remove the observerOneSignal.getUser().getPushSubscription().removeObserver(this);
// AppDelegate.swift// Add OSPushSubscriptionObserver after UIApplicationDelegateclass 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 observerOneSignal.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.addObserver((state) { if (state.current.optedIn) { /// respond to new state }});// Removes the previously added observerOneSignal.User.pushSubscription.removeObserver(myObserver);
const listener = (event: PushSubscriptionChangedState) => { console.log("Push subscription changed: " + (event));};// Add the listener - IonicOneSignal.User.pushSubscription.addEventListener("change", listener);// Remove the listener - IonicOneSignal.User.pushSubscription.removeEventListener("change", listener);// Add the listener - Cordovawindow.plugins.OneSignal.User.pushSubscription.addEventListener("change", listener);// Remove the listener - Cordovawindow.plugins.OneSignal.User.pushSubscription.removeEventListener("change", listener);
Control the subscription status (subscribed or unsubscribed) of the current push Subscription. Use these methods to control the push subscription status within your app. Common use cases: 1) Prevent push from being sent to users that log out. 2) Implement a notification preference center within your app.
optOut(): Sets the current push subscription status to unsubscribed (even if the user has a valid push token).
optIn(): Does one of three actions:
If the Subscription has a valid push token, it sets the current push subscription status to subscribed.
If the Subscription does not have a valid push token, it displays the push permission prompt.
If the push permission prompt has been displayed more than the operating system’s limit (once iOS, twice Android), it displays the fallback prompt.
optedIn: Returns true if the current push subscription status is subscribed, otherwise false. If the push token is valid but optOut() was called, this will return false.
Adds or removes an email Subscription (email address) to/from the current user. Call addEmail after login() to set the correct user context. Compatible with Identity Verification.
Adds or removes an SMS Subscription (phone number) to/from the current user. Requires E.164 format. Call addSms after login() to set the correct user context. Compatible with Identity Verification.
Shows the native system prompt asking the user for push notification permission. Optionally enable a fallback prompt that links to the settings app.
fallbackToSettings: If true, the fallback prompt will be displayed if the user denied push permissions more than the operating system’s limit (once iOS, twice Android).
// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionsOneSignal.Notifications.requestPermission(true)
// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionsOneSignal.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 }}));
// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionsOneSignal.Notifications.requestPermission({ accepted in print("User accepted notifications: \(accepted)")}, fallbackToSettings: true)
// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissions[OneSignal.Notifications requestPermission:^(BOOL accepted) { NSLog(@"User accepted notifications: %d", accepted);} fallbackToSettings:true];
// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionsvar result = await OneSignal.Notifications.RequestPermissionAsync(true);if (result){ // Notification permission was accepted.}else{ // Notification permission was denied.}
// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionsOneSignal.Notifications.requestPermission(true);
// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionsOneSignal.Notifications.requestPermission(true);
// Ionic// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionsOneSignal.Notifications.requestPermission(true).then((accepted) => { console.log("User accepted notifications: " + accepted);});// Cordova// We recommend removing this method after testing and instead use In-App Messages to prompt for notification permission.// Passing true will fallback to setting prompt if the user denies push permissionswindow.plugins.OneSignal.Notifications.requestPermission(true).then((accepted) => { console.log("User accepted notifications: " + accepted);});
Use this method to track push permission changes like:
The notification permission prompt is displayed to the user.
The user accepts or declines the permission prompt.
The user enables or disables notifications for your app in the device’s app settings and then returns to your app.
When this happens, the SDK triggers the onOSPermissionChanged event. Your listener receives a state object with the from and to values so you can detect exactly what changed.To stop listening for updates, call the associated removePermissionObserver() method.
class MyObserver : IPermissionObserver { init { OneSignal.Notifications.addPermissionObserver(this) } override fun onNotificationPermissionChange(granted: Boolean) { if (granted) { // Notifications are now enabled } } fun cleanup() { OneSignal.Notifications.removePermissionObserver(this) }}
public class MainActivity extends Activity implements IPermissionObserver { protected void onCreate(Bundle savedInstanceState) { OneSignal.getNotifications().addPermissionObserver(this); } @Override public void onNotificationPermissionChange(boolean granted) { if (granted) { // Notifications are now enabled } } @Override protected void onDestroy() { OneSignal.getNotifications().removePermissionObserver(this); super.onDestroy(); }}
const onPermissionChange = (granted) => { console.log('Permission changed:', granted);};OneSignal.Notifications.addEventListener('permissionChange', onPermissionChange);// Remove later if neededOneSignal.Notifications.removeEventListener('permissionChange', onPermissionChange);
final observer = (bool hasPermission) { print("Notification permission: $hasPermission");};OneSignal.Notifications.addPermissionObserver(observer);// Remove later if neededOneSignal.Notifications.removePermissionObserver(observer);
const listener = (granted) => { console.log("Push permission changed:", granted);};// IonicOneSignal.Notifications.addEventListener("permissionChange", listener);// Remove later if neededOneSignal.Notifications.removeEventListener("permissionChange", listener);// Cordovawindow.plugins.OneSignal.Notifications.addEventListener("permissionChange", listener);// Remove later if neededwindow.plugins.OneSignal.Notifications.removeEventListener("permissionChange", listener);
getPermission() returns the current push permission status at the app-level. It does not consider the OneSignal-level subscription status if you changed it via optOut() or the enabled parameter in the Users and Subscriptions APIs. Instead of using getPermission(), we recommend using the Push Permission Observer to track changes in the device’s notification permission status while the app is running or the Push Subscription Observer to track changes in the push subscription status.getCanRequestPermission() returns whether attempting to request permission will result in a prompt being displayed to the user. If false, the user has already denied permission and can either be shown the fallback prompt or no prompt at all. See Prompt for push permissions for more information.
// true if the app has permission to display notificationsOneSignal.Notifications.permission// true if the device can display system notification permission promptval canRequest: Boolean = OneSignal.Notifications.canRequestPermission
// true if the app has permission to display notificationsOneSignal.getNotifications().getPermission();// true if the device can display system notification permission promptOneSignal.getNotifications().getCanRequestPermission();
// true if the app has permission to display notificationsOneSignal.Notifications.permission// true if the device can display system notification permission promptOneSignal.Notifications.canRequestPermission
// true if the app has permission to display notifications[OneSignal.Notifications permission];// true if the device can display system notification permission prompt[OneSignal.Notifications canRequestPermission];
// true if the app has permission to display notificationsbool permission = OneSignal.Notifications.Permission;// true if the device can display system notification permission promptbool canRequest = OneSignal.Notifications.CanRequestPermission;
// true if the app has permission to display notificationsawait OneSignal.Notifications.getPermissionAsync();// true if the device can display system notification permission promptawait OneSignal.Notifications.canRequestPermissionAsync();
// true if the app has permission to display notificationsvar permission = OneSignal.Notifications.permission;// true if the device can display system notification permission promptvar canRequest = OneSignal.Notifications.canRequestPermission;
// Ionic// true if the app has permission to display notificationsawait OneSignal.Notifications.getPermissionAsync();// true if the device can display system notification permission promptawait OneSignal.Notifications.canRequestPermissionAsync();// Cordova// true if the app has permission to display notificationsawait window.plugins.OneSignal.Notifications.getPermissionAsync();// true if the device can display system notification permission promptawait window.plugins.OneSignal.Notifications.canRequestPermissionAsync();
Set a callback that runs when a user clicks a push notification that opens the app.The app’s activity or scene is already launched by the time this event fires. Use this handler to perform any custom logic — do not relaunch or duplicate app navigation manually.
For Flutter Apps, if the app is force-closed and you click a notification, the app will not open and the Click Listener will not register in Debug mode. To fix this, you can either:
Use a release build via Flutter e.g. flutter run --release (requires a physical device)
Update the Xcode scheme to be Release not Debug
Use removeClickListener() or removeEventListener() to stop listening when the handler is no longer needed.
val clickListener = object : INotificationClickListener { override fun onClick(event: INotificationClickEvent) { Log.d("OneSignal", "Notification clicked: ${event.notification.title}") }}OneSignal.Notifications.addClickListener(clickListener)
Allows you to intercept and control how notifications behave when the app is in the foreground.By default, OneSignal automatically displays the notification. You can override this behavior using event.preventDefault() to:
Suppress the notification
Customize it
Delay display for async logic (e.g., fetch user state, log events)
Call event.notification.display() to manually show it later.
Use removeForegroundLifecycleListener() or removeEventListener() to stop listening when the handler is no longer needed.
val lifecycleListener = object : INotificationLifecycleListener { override fun onWillDisplay(event: INotificationWillDisplayEvent) { Log.d("OneSignal", "Foreground notification: ${event.notification.title}") // Uncomment to prevent the notification from being displayed while in the foreground // event.preventDefault() }}OneSignal.Notifications.addForegroundLifecycleListener(lifecycleListener)
OneSignal.getNotifications().addForegroundLifecycleListener(new INotificationLifecycleListener() { @Override public void onWillDisplay(@NonNull INotificationWillDisplayEvent event) { Log.d("OneSignal", "Foreground notification received: " + event.getNotification().getTitle()); // Uncomment to prevent the notification from being displayed while in the foreground // event.preventDefault(); }});
class AppDelegate: UIResponder, UIApplicationDelegate, OSNotificationLifecycleListener { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { OneSignal.Notifications.addForegroundLifecycleListener(self) return true } func onWillDisplay(event: OSNotificationWillDisplayEvent) { print("Foreground notification: \(event.notification.title ?? "No Title")") // Uncomment to prevent the notification from being displayed while in the foreground // event.preventDefault() }}
@implementation AppDelegate- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [OneSignal.Notifications addForegroundLifecycleListener:self]; return YES;}- (void)onWillDisplayNotification:(OSNotificationWillDisplayEvent *)event { NSLog(@"Foreground notification: %@", event.notification.title); // Uncomment to prevent the notification from being displayed while in the foreground // [event preventDefault];}@end
OneSignal.Notifications.ForegroundWillDisplay += (sender, e) =>{ Console.WriteLine("Foreground notification: " + e.Notification.Title); // Uncomment to prevent the notification from being displayed while in the foreground // e.PreventDefault();};
OneSignal.Notifications.addEventListener('foregroundWillDisplay', (event) => { console.log("Foreground notification:", event.getNotification().title); // Uncomment to prevent the notification from being displayed while in the foreground // event.preventDefault();});
OneSignal.Notifications.addForegroundWillDisplayListener((event) { print("Foreground notification: ${event.notification.title}"); // Uncomment to prevent the notification from being displayed while in the foreground // event.preventDefault();});
const myLifecyleListener = function(event) { console.log("Foreground notification:", event.notification.title); // Uncomment to prevent the notification from being displayed while in the foreground // event.preventDefault();};// IonicOneSignal.Notifications.addEventListener("foregroundWillDisplay", myLifecyleListener);// Cordovawindow.plugins.OneSignal.Notifications.addEventListener("foregroundWillDisplay", myLifecyleListener);
Removes all OneSignal notifications from the Notification Shade. Use instead of Android’s android.app.NotificationManager.cancel. Otherwise, the notifications will be restored when your app is restarted.
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.
Cancel a group of OneSignal notifications with the provided group key. Grouping notifications is a OneSignal concept. There is no android.app.NotificationManager equivalent.
Decide when to display an In-App Message based on a single or multiple triggers. See Triggers for more information.Triggers are not persisted to the backend. They only exist on the local device and apply to the current user.
OneSignal.InAppMessages.addTrigger("KEY", "VALUE")OneSignal.InAppMessages.addTriggers(mapOf("KEY_01" to "VALUE_01", "KEY_02" to "VALUE_02"))
Prevent In-app messages from being displayed to the user. When set to true, no in-app messages will be presented. When set to false, any messages the user qualifies for will be presented to them at the appropriate time.
OneSignal.InAppMessages.paused = true
OneSignal.getInAppMessages().setPaused(true);
OneSignal.InAppMessages.paused = true// Get `paused` statelet paused = OneSignal.InAppMessages.paused
[OneSignal.InAppMessages paused:true];// Get `paused` stateBOOL paused = [OneSignal.InAppMessages paused];
// 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 onDidDismiss(event: OSInAppMessageDidDisplayEvent) { print("OSInAppMessageLifecycleListener: onDidDismiss Message: \(event.message.messageId)") }}
// 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);}
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 functionslet 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// IonicOneSignal.InAppMessages.addEventListener("willDisplay", willDisplayListener);OneSignal.InAppMessages.addEventListener("didDisplay", didDisplayListener);OneSignal.InAppMessages.addEventListener("willDismiss", willDismissListener);OneSignal.InAppMessages.addEventListener("didDismiss", didDismissListener);// Cordovawindow.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);
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.
Allows OneSignal to manage the lifecycle of a LiveActivity on behalf of the application. This includes listening for both pushToStart token updates and pushToUpdate token updates.
//... your app's codeOneSignal.LiveActivities.setup(MyWidgetAttributes.self);
Allows cross platform SDK’s to manage the lifecycle of a LiveActivity by eliminating the need for a customer app to define and manage their own ActivityAttributes. See Cross-platform setup for further details.
using OneSignalSDK;//Push To StartOneSignal.LiveActivities.SetupDefault();//Launching the Live Activity from within the app (not needed for push to start)string activityId = "my_activity_id";OneSignal.LiveActivities.StartDefault( activityId, new Dictionary<string, object>() { { "title", "Welcome!" } }, new Dictionary<string, object>() { { "message", new Dictionary<string, object>() { { "en", "Hello World!"} }}, });
import { OneSignal } from 'react-native-onesignal'//Push To StartOneSignal.LiveActivities.setupDefault()//Launching the Live Activity from within the app (not needed for push to start)const activityId = "my_activity_id"const attributes = { title: "Sample Title" } ;const content = { message: { en: "message" } };OneSignal.LiveActivities.startDefault(activityId, attributes, content);
import 'package:onesignal_flutter/onesignal_flutter.dart';OneSignal.LiveActivities.setupDefault()//Launching the Live Activity from within the app (not needed for push to start)const String activityId = "my_activity_id";OneSignal.LiveActivities.startDefault(activityId!, { "title": "Welcome!" }, { "message": {"en": "Hello World!"},});
//Ionicimport OneSignal from "onesignal-cordova-plugin";//Push To StartOneSignal.LiveActivities.setupDefault();//Launching the Live Activity from within the app (not needed for push to start)const activityId = "my_activity_id";const attributes = { title: "Sample Title" };const content = { message: { en: "message" } };OneSignal.LiveActivities.startDefault(activityId, attributes, content);//Cordova//Push To Startwindow.plugins.OneSignal.LiveActivities.setupDefault();//Launching the Live Activity from within the app (not needed for push to start)const activityId = "my_activity_id";const attributes = { title: "Sample Title" };const content = { message: { en: "message" } };window.plugins.OneSignal.LiveActivities.startDefault( activityId, attributes, content);
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 codelet activity = try Activity<MyWidgetAttributes>.request( attributes: attributes, contentState: contentState, pushType: .token)Task { for await data in activity.pushTokenUpdates { let token = data.map {String(format: "%02x", $0)}.joined() // ... required code for entering a live activity // Activity ID cannot contain "/" characters OneSignal.LiveActivities.enter("ACTIVITY_ID", withToken: token) }}
var result = OneSignalSDK.DotNet.OneSignal.Default.EnterLiveActivity("ACTIVITY_ID", token);if(result) { Console.WriteLine("Success");}
OneSignal.LiveActivities.enter('ACTIVITY_ID', token, (result) => { console.log('Results of entering live activity: ', result);});
OneSignal.LiveActivities.enterLiveActivity("ACTIVITY_ID", token).then((result) { print("Successfully enter live activity");}).catchError((error) { print("Failed to enter live activity with error: $error");});
//IonicOneSignal.LiveActivities.enter("ACTIVITY_ID", token, (result) => { console.log("Results of entering live activity: ", result);});//Cordovawindow.plugins.OneSignal.LiveActivities.enter("ACTIVITY_ID", token, (result) => { console.log("Results of entering live activity: ", result);});
OneSignal.LiveActivities.exit('ACTIVITY_ID', (result) => { console.log('Results of exiting live activity: ', result);});
OneSignal.LiveActivities.exit("ACTIVITY_ID").then((result) { print("Successfully exit live activity");}).catchError((error) { print("Failed to exit live activity: $error");});
window.plugins.OneSignal.LiveActivities.exit("ACTIVITY_ID", (result) => { console.log("Results of exiting live activity: ", result);});
Optional “low-level” approach to push to start live activities. Offers fine-grained control over the LiveActivity start and update tokens without altering the ActivityAttribute structure. Additional details available here
if #available(iOS 17.2, *) { // Setup an async task to monitor and send pushToStartToken updates to OneSignalSDK. Task { for try await data in Activity<MyWidgetAttributes>.pushToStartTokenUpdates { let token = data.map {String(format: "%02x", $0)}.joined() OneSignal.LiveActivities.setPushToStartToken(MyWidgetAttributes.self, withToken: token) } } // Setup an async task to monitor for an activity to be started, for each started activity we // can then set up an async task to monitor and send updateToken updates to OneSignalSDK. Task { for await activity in Activity<MyWidgetAttributes>.activityUpdates { Task { for await pushToken in activity.pushTokenUpdates { let token = pushToken.map {String(format: "%02x", $0)}.joined() OneSignal.LiveActivities.enter("my-activity-id", withToken: token) } } } }}