Mobile SDKs

OneSignal Mobile SDKs Version 5.0.0+ User Model Methods

๐Ÿ“˜

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 the SDK

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

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 websites, see Debugging with Browser Tools.

Set the log level

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

Set the alert level

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

User

OneSignal creates and stores user-level data under a unique ID called onesignal_id. Users can have multiple subscription records (subscription_id) based on how many channels they subscribe to with your OneSignal app. More details in:

Log in a user

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

Log out a user

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

Add an alias

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

Add multiple aliases

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

Remove an alias

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

Remove multiple aliases

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

User Data

Use the push permission observer and/or subscription observer to react to changes, like updating your server when the user's subscription state changes to fetch their Subscription ID.

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


Language

Set the language

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. See Data Tags Overview for more details on what tags are used for.

See Data Tag Implementation for SDK Method details.


Privacy

Require privacy consent

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

Provide user consent

Sets whether privacy consent has been granted.

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

๐Ÿ“˜

Required when consentRequired is true

The SDK will not be fully enabled until consentGiven is true. Calling SDK methods like sendTags will result in a no-op until you explicitly inform the SDK the user has consented to.


Location

Enable location sharing

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

Get shared location status

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

Request location permission

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

Get push notification permissions

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

Get device's native permission status (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()

Prompt for push notification permissions

iOS requires prompting users for permission to show push notifications that make sound and "pop-up" 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 different behavior from previous Android versions. More details 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.

Check if permission prompt can be displayed

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

Observe push permission changes

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

This includes the following events:

  • Notification permission prompt 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 method, 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);

Remove permissions observer

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

Observe push subscription changes

Add a listener to run when a notification subscription property changes.

This includes the following events:

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

Set notification click listeners

Set a handler that will run whenever the 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);

Handle notifications before displayed when the app is in the foreground

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.

Remove a notification (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);

Remove grouped notifications (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");

Clear all notifications

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

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

Push 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();

Disable a push subscription

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

Enable a push subscription

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

Get push subscription status

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.

Add an Outcome

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

Add a Unique Outcome

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

Add a Unique Outcome with a captured value

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 to get started, but if you would like to setup the custom triggers to display the In-App Message under certain conditions and track IAM lifecycle events, we have SDK methods for you!

See In-App Message SDK Methods for more details.


Email

OneSignal's Mobile and Web SDKs provide methods for collecting emails, logging out of emails, and tracking email subscription changes.

See Email SDK Methods for more details.


SMS

OneSignal's Mobile and Web SDKs provide methods for collecting phone numbers, logging out phone numbers, and tracking SMS subscriptions.

See SMS SDK Methods for more details.


Live Activities

Live Activities are a type of interactive push notification. Designed by Apple to enable iOS apps to provide real-time updates to their users that are visible from the lock screen and dynamic island.

See Live Activities SDK Methods for more details.