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.
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:
Don't see your platform below?
We have several SDKs with different options for initialization within. Please see the platform-specific doc if you don't see your particular platform below.
Initializing 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, so you can call it before initializing OneSignal. For websites, see Debugging with Browser Tools.
Setting 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);
Setting the alert level
Sets the logging level to show as alert dialogs.
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 subscription-level data under a unique ID called onesignal_id
. Users can have multiple subscription records based on how many channels they subscribe to with your OneSignal app.
Logging in a user
Login to OneSignal under the user identified by the external_id
provided. Logging a user into the OneSignal SDK will switch the context to that specific user.
- If the
external_id
exists, the user will be retrieved, and the context will be set from that user information. If operations have already been performed under an anonymous user, they will not be applied to the now logged-in user, and their information will be lost. - If the
external_id
does not exist, the user will be created, and the context will be set from the current local state. If operations have already been performed under an anonymous user, those operations will be applied to the newly created user.
Logging in a new user will automatically transfer the push notification and in-app messaging subscriptions from the current user to the newly logged-in user. This is because the device owns both push notifications and in-app messages.
The login
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");
Use Identity Verification
If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an Identifier Authentication Token and send it to your site.
Logging out a user
Log out the user previously logged in via thelogin
method. The user
property 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();
Adding an alias
Set an alias for the current user. If the alias label exists on this user, it will be overwritten.
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");
Adding multiple aliases
Set aliases for the current user. If any alias labels exist on the user, they will be overwritten.
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"});
Removing 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");
Removing 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 permission and push subscription observers 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.
To respond to user push subscription changes, see Responding to push subscription changes; to respond to notification permission changes, refer to Handling Notification Permission Changes
Language
Setting the language
Set the language for the user using 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
Opting into data privacy protections
Determines whether users must consent to privacy 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);
GDPR users should set this property to
true
Providing 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 trueThe SDK will not be fully enabled until
consentGiven
istrue
. Calling SDK methods likesendTags
will result in a no-op until you explicitly inform the SDK the user has consented to.
Location
Enabling 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.
// 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.setLocationShared(true)
OneSignal.Location.IsShared = true;
OneSignal.Location.setShared(true);
OneSignal.Location.setShared(true);
window.plugins.OneSignal.Location.setShared(true);
Setting the property to false
will disable location sharing.
Getting 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.isLocationShared()
bool isShared = OneSignal.Location.IsShared;
OneSignal.Location.isShared();
OneSignal.Location.isShared();
window.plugins.OneSignal.Location.isShared(isShared => {
console.log("Location shared: ", isShared);
});
isLocationShared
default valueThis property defaults to true if your app has location permission.
Requesting location permission
Prompt the user for location permissions to allow geotagging.
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();
Soft-prompting for permission
Use an In-App Message to soft-prompt before displaying the Native Alert. Details: Location Opt-In Prompt.
Configuring location on Android
- 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" />
- Add the location dependency.
dependencies {
...
implementation 'com.google.android.gms:play-services-location:YOUR_PLAY_SERVICES_VERSION'
}
Configuring 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
Checking push notification permissions
Determine whether the app has notification permission.
This 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, seeOneSignal.User.PushSubscription
for these.
OneSignal.getNotifications().getPermission();
OneSignal.Notifications.permission
[OneSignal.Notifications permission];
OneSignal.Notifications.permission
bool permission = OneSignal.Notifications.Permission;
let permission = OneSignal.Notifications.hasPermission()
var permission = OneSignal.Notifications.permission;
// Cordova
let permission = window.plugins.OneSignal.Notifications.hasPermission()
// Capacitor/Ionic
let permission = OneSignal.Notifications.hasPermission()
Prompting 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:
- Recommended: use OneSignal's In-App Message Soft-Prompt before displaying the Native Alert. Details: Prompting for Push Permissions Guide.
- Programmatically Trigger the Native Alert Prompt with the OneSignal SDK
promptForPushNotifications
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);
});
Checking if a permissions 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);
});
Observing permission changes
Handling Notification 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 (iOS)
- The user accepting or declining the permission prompt (iOS)
- Enabling or disabling notifications for your app in the App Settings and after returning to your app
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 OSPermissionObserver)
}
// 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.addPermissionObserver((granted) => {
console.log('OneSignal: permission changed:', granted.permission);
});
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);
Removing 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);
Setting 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);
Handling notifications before they're presented 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.
Removing 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);
Removing 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");
Clearing 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.
Responding to push subscription changes
The onPushSubscriptionDidChange
method will be fired on the passed-in object when a notification subscription property changes.
This includes the following events:
- Getting a push token from Google or Apple
- Getting a subscription id from OneSignal
optedIn
is manually changed- User disables or enables notification permissions
The changed state object is given to your onPushSubscriptionDidChange
method, which provides what the value was ("previous") and what the value is now ("current").
public class MainActivity extends Activity implements IPushSubscriptionObserver {
protected void onCreate(Bundle savedInstanceState) {
OneSignal.getUser().getPushSubscription().addObserver(this);
}
@Override
public void onPushSubscriptionChange(@NonNull PushSubscriptionChangedState state) {
// respond to permission state change
}
}
class MyObserver : IPushSubscriptionObserver {
init {
OneSignal.User.pushSubscription.addObserver(this)
}
override fun onPushSubscriptionChange(state: PushSubscriptionChangedState) {
val pushToken = state.current.token
if (state.current.optedIn) {
// Respond to user subscribed
}
}
}
// AppDelegate.swift
// Add OSPermissionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSPushSubscriptionObserver {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Add your AppDelegate as an obsserver
OneSignal.User.pushSubscription.addObserver(self)
}
// Add this new method
func onPushSubscriptionDidChange(state: OneSignalUser.OSPushSubscriptionChangedState) {
//respond to state change
}
}
// AppDelegate.h
// Add OSPermissionObserver 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
- (void)onPushSubscriptionDidChangeWithState:(OSPushSubscriptionChangedState *)state {
//respond to new state
}
@end
OneSignal.User.PushSubscription.Changed += (sender, e) =>
{
if (e.State.Current.Id != e.State.Previous.Id)
{
// OneSignal Subscription id changed.
}
};
OneSignal.User.PushSubscription.addObserver((subscription) => {
console.log('OneSignal: subscription changed:', subscription);
});
OneSignal.User.pushSubscription.addObserver((state) {
if (state.current.optedIn) {
/// respond to new state
}
});
let observer = function(req) {
console.log("Subscription observer with callback " + (req));
};
window.plugins.OneSignal.User.pushSubscription.addObserver(observer);
To send notifications to users, we recommend using the Create notification REST API docs or Messages Dashboard.
Outcomes
Track actions taken by users and attribute them to messages. See Outcomes for more details.
Adding 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");
Adding 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");
Adding 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);
Push Subscription
Subscription ID
The user's push subscription ID. See Subscriptions for more details.
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;
const id = await OneSignal.User.PushSubscription.getPushSubscriptionId();
OneSignal.User.pushSubscription.id;
let id = window.plugins.OneSignal.User.pushSubscription.id;
Push Token
The subscription's push token. Required to receive push notifications.
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;
const token = await OneSignal.User.PushSubscription.getPushSubscriptionToken();
OneSignal.User.pushSubscription.token;
let token = window.plugins.OneSignal.User.pushSubscription.token;
Disabling 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();
Enabling a push subscription
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:
- OneSignal.Notifications.permission is
true
. - 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();
Checking push subscription status
Whether the user has opted into push notifications
Boolean optedIn = OneSignal.getUser().getPushSubscription().optedIn();
val optedIn = OneSignal.User.subscriptions.push.optedIn
bool optedIn = OneSignal.User.pushSubscription.optedIn
let optedIn: Bool = OneSignal.User.pushSubscription.token
OneSignal.User.PushSubscription.OptedIn;
const optedIn = await OneSignal.User.PushSubscription.getOptedIn();
OneSignal.User.pushSubscription.optedIn;
let optedIn = window.plugins.OneSignal.User.pushSubscription.optedIn;
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.
Updated 1 day ago