OneSignal Help & Documentation

Welcome to the OneSignal New IA developer hub. You'll find comprehensive guides and documentation to help you start working with OneSignal New IA as quickly as possible, as well as support if you get stuck. Let's jump right in!

Get Started    Discussions

SDK Reference

Comprehensive reference of OneSignal's SDK methods

Some methods below require the OneSignal SDK Versions:

  • Android 4.0.0+
  • iOS 3.0.0+
  • React Native 4.0.0+
  • Flutter 3.0.0+
  • Cordova/Ionic 3.0.0+

See Mobile SDKs API Migration Guides to upgrade the OneSignal SDK or the old SDK Reference.

Debugging

setLogLevel Method

Enable logging to help debug if you run into an issue setting up OneSignal. This selector is static, so you can call it before OneSignal init.

Parameters

Type

Description

logLevel

LOG_LEVEL

Sets the logging level to print to the Android LogCat log or Xcode log.

visualLevel

LOG_LEVEL

Sets the logging level to show as alert dialogs.

//The following options are available with increasingly more information:
//NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
OneSignal.setLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
//The following options are available with increasingly more information: 
//.LL_NONE, .LL_FATAL, .LL_ERROR, .LL_WARN, .LL_INFO, .LL_DEBUG, .LL_VERBOSE.
OneSignal.setLogLevel(.LL_VERBOSE, visualLevel: .LL_NONE)
////The following options are available with increasingly more information: 
//ONE_S_LL_NONE, ONE_S_LL_FATAL, ONE_S_LL_ERROR, ONE_S_LL_WARN, ONE_S_LL_INFO, ONE_S_LL_DEBUG, ONE_S_LL_VERBOSE.
[OneSignal setLogLevel:ONE_S_LL_VERBOSE visualLevel:ONE_S_LL_NONE];
//The following options are available with increasingly more information:
//NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
OneSignal.SetLogLevel(OneSignal.LOG_LEVEL.VERBOSE, OneSignal.LOG_LEVEL.NONE);
//The following options are available with increasingly more information: 
//0 = NONE, 1 = FATAL, 2 = ERROR, 3 = WARN, 4 = INFO, 5 = DEBUG, 6 = VERBOSE
OneSignal.setLogLevel(6, 0);
//The following options are available with increasingly more information: 
//0 = NONE, 1 = FATAL, 2 = ERROR, 3 = WARN, 4 = INFO, 5 = DEBUG, 6 = VERBOSE
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.setLogLevel({logLevel: 6, visualLevel: 0});
//The following options are available with increasingly more information:
//none, fatal, error, warn, info, debug, verbose
OneSignal.shared.setLogLevel(OSLogLevel.verbose, OSLogLevel.none);
//The following options are available with increasingly more information:
//NONE, FATAL, ERROR, WARN, INFO, DEBUG, VERBOSE
// Needs: using Com.OneSignal.Abstractions;
OneSignal.Current.SetLogLevel(LOG_LEVEL.VERBOSE, LOG_LEVEL.NONE);
-- The following options are available with increasingly more information:
--0 = NONE, 1 = FATAL, 2 = ERROR, 3 = WARN, 4 = INFO, 5 = DEBUG, 6 = VERBOSE
OneSignal.SetLogLevel(6, 0)

iOS Push Prompting

iOS Apps have a native Alert Prompt that must be displayed and the user must authorize permission for your app to send them push notifications. iOS also supports Provisional Push Notifications.

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


External User Ids

OneSignal creates and stores device & channel level data under a unique OneSignal Id called the player_id. A single user can have multiple player_id records based on how many devices, email addresses, and phone numbers they use to interact with your app/site.

You can combine player_id records in OneSignal under a unique User Id called the external_user_id.

See the External User Ids guide for more details.

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.


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.


User Data

Methods to get the OneSignal Player ID, subscription status, prompt status and push token.

Use addPermissionObserver or addSubscriptionObserver to react to changes. For example, update your server when the user becomes subscribed or unsubscribed, and to get the OneSignal Player Id.

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

getDeviceState Method

Returns an OSDeviceState object with the current immediate device state info. If called too early will be null or no available. - Use to load your UI to the correct state. Such as showing a toggle button to enable notifications.

OSDeviceState device = OneSignal.getDeviceState();

String userId = device.getUserId();//push player_id
String emailUserId = device.getEmailUserId();//email player_id
String smsUserId = device.getSMSUserId();//sms player_id

String emailAddress = device.getEmailAddress();
String smsNumber = device.getSMSNumber();
String getPushToken = device.getPushToken();

boolean areNotificationsEnabled = device.areNotificationsEnabled();
boolean isSubscribed = device.isSubscribed();//Push Subscription Status
boolean isPushDisabled = device.isPushDisabled();//Is push disabled with disablePush method

boolean isEmailSubscribed = device.isEmailSubscribed();
boolean isSMSSubscribed = device.isSMSSubscribed();
if let deviceState = OneSignal.getDeviceState() {
    let emailAddress = deviceState.emailAddress
    print("Email Address tied to this device with setEmail: ", emailAddress ?? "called too early or not set yet" )
    let emailUserId = deviceState.emailUserId
    print("OneSignal Email player ID: ", emailUserId ?? "called too early or not set yet")
    let hasNotificationPermission = deviceState.hasNotificationPermission
    print("Has device allowed push permission at some point: ", hasNotificationPermission)
    let isEmailSubscribed = deviceState.isEmailSubscribed
    print("is the email address tied to this record subscribed to receive email: ", isEmailSubscribed)
    let isPushDisabled = deviceState.isPushDisabled
    print("Push notifications are disabled with disablePush method: ", isPushDisabled)
    let isSMSSubscribed = deviceState.isSMSSubscribed
    print("is the phone number tied to this record subscribed to receive sms: ", isSMSSubscribed)
    let isSubscribed = deviceState.isSubscribed
    print("Device is subscribed to push notifications: ", isSubscribed)
    let notificationPermissionStatus = deviceState.notificationPermissionStatus.rawValue
    print("Device's notification permission status: ", notificationPermissionStatus)
    let pushToken = deviceState.pushToken
    print("Device's push token: ", pushToken ?? "called too early or not set yet" )
    let smsNumber = deviceState.smsNumber
    print("Phone Number tied to this device with setSMSNumber: ", smsNumber ?? "called too early or not set yet" )
    let smsUserId = deviceState.smsUserId
    print("OneSignal SMS player ID: ", smsUserId ?? "called too early or not set yet")
    let userId = deviceState.userId
    print("OneSignal Push Player ID: ", userId ?? "called too early, not set yet")
}
OSDeviceState *deviceState = [OneSignal getDeviceState];
NSString *userId = deviceState.userId; //push player_id
NSString *pushToken = deviceState.pushToken;
BOOL subscribed = deviceState.isSubscribed;
//See GetPermissionSubscriptionState method: 
//https://documentation.onesignal.com/v7.0/docs/unity-sdk#getpermissionsubscriptionstate
var status = OneSignal.GetPermissionSubscriptionState();
status.permissionStatus.hasPrompted;
status.permissionStatus.status;

status.subscriptionStatus.subscribed;
status.subscriptionStatus.userSubscriptionSetting;
status.subscriptionStatus.userId;
status.subscriptionStatus.pushToken;
const deviceState = await OneSignal.getDeviceState();
OneSignal.shared.getDeviceState().then((deviceState) {
     print("OneSignal: device state: ${deviceState.jsonRepresentation()}");
});
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.getDeviceState(function(stateChanges) {
  console.log('OneSignal getDeviceState: ' + JSON.stringify(stateChanges));
});

OSDeviceState

Type

Method/Property

Description

String
NSString

getUserId()
userId

Get the OneSignal Push Player Id.

String
NSString

getEmailUserId()
emailUserId

Get the OneSignal Email Player Id.
Only available if OneSignal.setEmail() was called.

String
NSString

getSMSUserId()
smsUserId

Get the OneSignal SMS Player Id.
Only available if OneSignal.getSMSNumber() was called.

String
NSString

getEmailAddress()
emailAddress

Get the email address tied to the device.
Only available if OneSignal.setEmail() was called.

String
NSString

getSMSNumber()
smsNumber

Get the SMS Phone Number tied to the device.
Only available if OneSignal.setSMSNumber() was called.

String
NSString

getPushToken()
pushToken

Get device's push token identifier.

Bool

areNotificationsEnabled() (Android)
hasNotificationPermission (iOS)

Get whether notifications are enabled on the device at the app level.

Android: this is the same value as areNotificationsEnabled() method.

Bool

isSubscribed()
isSubscribed

Get whether the device is subscribed to receive OneSignal push notifications.

Bool

isPushDisabled()
isPushDisabled

Returns the value of what was sent to OneSignal.disablePush(bool).
False by default.

Bool

isEmailSubscribed()
isEmailSubscribed

If the email address passed into setEmail for the device is subscribed to email.

Bool

isSMSSubscribed()
isSMSSubscribed

If the phone number passed into setSMSNumber for the device is subscribed to SMS.

Integer

notificationPermissionStatus

Current notification permission status of the device.

0 - "NotDetermined" - The user hasn't yet made a choice about whether the app is allowed to schedule notifications.

1 - "Denied" - The app isn't authorized to schedule or receive notifications.

2 - "Authorized" - The app is authorized to schedule or receive notifications.

3 - "Provisional" - The application is provisionally authorized to post noninterruptive user notifications. See iOS Customizations

4 - "Ephemeral" - For App Clips. The app is authorized to schedule or receive notifications for a limited amount of time.

addPermissionObserver Method

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 shown (iOS)
  • The user accepting or declining the permission prompt (iOS)
  • Enabling or disabling notifications for your app in the App Settings and after returning to your app

Instance is given to your onOSPermissionChanged method, which provides what the value was ("from") and what the value is now ("to").

Any object implementing the OSPermissionObserver and/or the OSSubscriptionObserver protocols can be added as an observer. You can call removePermissionObserver to remove any existing listeners.

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

public class MainActivity extends Activity implements OSPermissionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addPermissionObserver(this);
  }
  
  public void onOSPermissionChanged(OSPermissionStateChanges stateChanges) {
    if (stateChanges.getFrom().getEnabled() &&
        !stateChanges.getTo().getEnabled()) {
         new AlertDialog.Builder(this)
             .setMessage("Notifications Disabled!")
             .show();
      }
   
      Log.i("Debug", "onOSPermissionChanged: " + stateChanges);
  }
}

// Example Logcat entry - User disabling notifications then returning to your app.
// onOSPermissionChanged{"from":{"enabled":true},"to":{"enabled":false}}
// AppDelegate.swift
// Add OSPermissionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSPermissionObserver {

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

   // Add this new method
   func onOSPermissionChanged(_ stateChanges: OSPermissionStateChanges!) {
      // Example of detecting answering the permission prompt
      if stateChanges.from.status == OSNotificationPermission.notDetermined {
         if stateChanges.to.status == OSNotificationPermission.authorized {
            print("Thanks for accepting notifications!")
         } else if stateChanges.to.status == OSNotificationPermission.denied {
            print("Notifications not accepted. You can turn them on later under your iOS settings.")
         }
      }
      // prints out all properties
      print("PermissionStateChanges: \n\(stateChanges)")
   }

   // Output:
   /*
   Thanks for accepting notifications!
   PermissionStateChanges:
   Optional(<OSSubscriptionStateChanges:
   from: <OSPermissionState: hasPrompted: 0, status: NotDetermined>,
   to:   <OSPermissionState: hasPrompted: 1, status: Authorized>
   >
   */
}
// AppDelegate.h
// Add OSPermissionObserver after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSPermissionObserver>
@end

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

// Add this new method
- (void)onOSPermissionChanged:(OSPermissionStateChanges*)stateChanges {
  
    // Example of detecting anwsering the permission prompt
    if (stateChanges.from.status == OSNotificationPermissionNotDetermined) {
      if (stateChanges.to.status == OSNotificationPermissionAuthorized)
         NSLog(@"Thanks for accepting notifications!");
      else if (stateChanges.to.status == OSNotificationPermissionDenied)
         NSLog(@"Notifications not accepted. You can turn them on later under your iOS settings.");
    }
    
   // prints out all properties 
   NSLog(@"PermissionStateChanges:\n%@", stateChanges);
}

// Output:
/*
Thanks for accepting notifications!
PermissionStateChanges:
<OSSubscriptionStateChanges:
from: <OSPermissionState: hasPrompted: 1, status: NotDetermined>,
to:   <OSPermissionState: hasPrompted: 1, status: Authorized>
>
*/

@end
OneSignal.permissionObserver += OneSignal_permissionObserver;

private void OneSignal_permissionObserver(OSPermissionStateChanges stateChanges) {
       // Example of detecting anwsering the permission prompt
    if (stateChanges.from.status == OSNotificationPermission.NotDetermined) {
      if (stateChanges.to.status == OSNotificationPermission.Authorized)
         Debug.Log("Thanks for accepting notifications!");
      else if (stateChanges.to.status == OSNotificationPermission.Denied)
         Debug.Log("Notifications not accepted. You can turn them on later under your device settings.");
    }
   
    Debug.Log("stateChanges.to.status: " + stateChanges.to.status);
}
OneSignal.addPermissionObserver(event => {
    console.log("OneSignal: permission changed:", event);
});
OneSignal.shared.setPermissionObserver((OSPermissionStateChanges changes) {
    // will be called whenever the permission changes
  
  if (changes.to.status == OSNotificationPermission.authorized) {
    //tells you that the user has fully authorized push permissions
  }
});
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.addPermissionObserver(function(state) {
  console.log("Notification permission state changed: " + state.hasPrompted);
  console.log("Notification permission status: " + state.status);
});
//Currently not available, use the idsAvailableCallback and check if a pushtoken is provided to make sure the user is subscribed

addSubscriptionObserver Method

The onOSSubscriptionChanged method will be fired on the passed-in object when a notification subscription property changes.

This includes the following events:

  • Getting a push token from Google or Apple
  • Getting a player/user id from OneSignal
  • OneSignal.disablePush is called
  • User disables or enables notifications

The instance is given to your onOSSubscriptionChanged method which provides what the value was ("from") and what the value is now ("to").

Any object implementing the OSPermissionObserver and/or the OSSubscriptionObserver protocols can be added as an observer. You can call removePermissionObserver to remove any existing listeners.

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

public class MainActivity extends Activity implements OSSubscriptionObserver {
  protected void onCreate(Bundle savedInstanceState) {
    OneSignal.addSubscriptionObserver(this);
  }
  
  public void onOSSubscriptionChanged(OSSubscriptionStateChanges stateChanges) {
    if (!stateChanges.getFrom().getSubscribed() &&
        stateChanges.getTo().getSubscribed()) {
         new AlertDialog.Builder(this)
             .setMessage("You've successfully subscribed to push notifications!")
             .show();
        // get player ID
        stateChanges.getTo().getUserId();
      }
   
      Log.i("Debug", "onOSSubscriptionChanged: " + stateChanges);
  }
}

/*
Example Logcat entry - User disabling notifications then returning to your app.
onOSSubscriptionChanged:
{"from":{"pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":false},
 "to":  {"userId":"22712a53-9b5c-4eab-a828-f18f81167fef","pushToken":"APA91bG9cmZ262s5gJhr8jvbg1q7aiviEC6lcOCgAQliEzHKO3eOdX5cm7IQqMSWfy8Od7Ol3jSjFfvCfeO2UYUpanJCURJ8RdhgEuV8grYxOCwPNJr5GoqcWTQOaL9u-qE2PQcFlv4K","userSubscriptionSetting":true,"subscribed":true}}
// AppDelegate.swift
// Add OSSubscriptionObserver after UIApplicationDelegate
class AppDelegate: UIResponder, UIApplicationDelegate, OSSubscriptionObserver {

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

   // Add this new method
   func onOSSubscriptionChanged(_ stateChanges: OSSubscriptionStateChanges!) {
      if !stateChanges.from.subscribed && stateChanges.to.subscribed {
         print("Subscribed for OneSignal push notifications!")
         // get player ID
         stateChanges.to.userId
      }
      print("SubscriptionStateChange: \n\(stateChanges)")
   }

   // Output:
   /*
   Subscribed for OneSignal push notifications!
   PermissionStateChanges:
   Optional(<OSSubscriptionStateChanges:
   from: <OSSubscriptionState: userId: (null), pushToken: 0000000000000000000000000000000000000000000000000000000000000000 userSubscriptionSetting: 1, subscribed: 0>,
   to:   <OSSubscriptionState: userId: 11111111-222-333-444-555555555555, pushToken: 0000000000000000000000000000000000000000000000000000000000000000, userSubscriptionSetting: 1, subscribed: 1>
   >
   */
}
// AppDelegate.h
// Add OSSubscriptionObserver after UIApplicationDelegate
@interface AppDelegate : UIResponder <UIApplicationDelegate, OSSubscriptionObserver>
@end

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

// Add this new method
- (void)onOSSubscriptionChanged:(OSSubscriptionStateChanges*)stateChanges {
  
    // Example of detecting subscribing to OneSignal
    if (!stateChanges.from.subscribed && stateChanges.to.subscribed) {
      NSLog(@"Subscribed for OneSignal push notifications!");
      // get player ID
      stateChanges.to.userId;
    }
    
   // prints out all properties
   NSLog(@"SubscriptionStateChanges:\n%@", stateChanges);
}

// Output:
/*
Subscribed for OneSignal push notifications!
PermissionStateChanges:
<OSSubscriptionStateChanges:
from: <OSSubscriptionState: userId: (null), pushToken: 0000000000000000000000000000000000000000000000000000000000000000 userSubscriptionSetting: 1, subscribed: 0>,
to:   <OSSubscriptionState: userId: 11111111-222-333-444-555555555555, pushToken: 0000000000000000000000000000000000000000000000000000000000000000, userSubscriptionSetting: 1, subscribed: 1>
>
*/

@end
//More details: https://documentation.onesignal.com/docs/unity-sdk#section-subscription-observer
OneSignal.subscriptionObserver += OneSignal_subscriptionObserver;

private void OneSignal_subscriptionObserver(OSSubscriptionStateChanges stateChanges) {
      Debug.Log("stateChanges: " + stateChanges);
      Debug.Log("stateChanges.to.userId: " + stateChanges.to.userId);
      Debug.Log("stateChanges.to.subscribed: " + stateChanges.to.subscribed);
   }
OneSignal.addSubscriptionObserver(event => {
  console.log("OneSignal: subscription changed event:", event);
  console.log("OneSignal: subscription changed from userId:", event.from.userId);
  console.log("OneSignal: subscription changed to userId:", event.to.userId);
  console.log("OneSignal: subscription changed from pushToken:", event.from.pushToken);
  console.log("OneSignal: subscription changed to pushToken:", event.to.pushToken);
  console.log("OneSignal: subscription changed from isPushDisabled:", event.from.isPushDisabled);
  console.log("OneSignal: subscription changed to isPushDisabled:", event.to.isPushDisabled);
  console.log("OneSignal: subscription changed from isSubscribed:", event.from.isSubscribed);
  console.log("OneSignal: subscription changed to isSubscribed:", event.to.isSubscribed);
});
//More details: https://documentation.onesignal.com/docs/flutter-sdk#section--setsubscriptionobserver-
OneSignal.shared.setSubscriptionObserver((OSSubscriptionStateChanges changes) {
  //will be called whenever the OS subscription changes
});
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.addSubscriptionObserver(function (state) {
  if (!state.from.subscribed && state.to.subscribed) {
    console.log("Subscribed for OneSignal push notifications!")
    // get player ID
    state.to.userId
  }
  console.log("Push Subscription state changed: " + JSON.stringify(state));
});
//Currently not available, use the idsAvailableCallback and check if a pushtoken is provided to make sure the user is subscribed: https://documentation.onesignal.com/docs/xamarin-sdk#section--idsavailablecallback-

setLanguage Method

Language is detected and set automatically through the OneSignal SDK based on the device settings. This method allows you to change that language by passing in the 2-character, lowercase language code. See Supported Languages.

//Requires SDK 3.16.0+
OneSignal.setLanguage("es");
//Requires SDK 3.6.0+
OneSignal.setLanguage("es")
//Requires SDK 3.6.0+
[OneSignal setLanguage:@"es"];
//Coming soon
//Requires SDK 3.2.0+
OneSignal.setLanguage("es");
//Requires SDK 4.2.0+
OneSignal.setLanguage("es");

Privacy

setRequiresUserPrivacyConsent Method

For GDPR users, your application should call this method before initialization of the SDK.

If you pass in true, your application will need to call provideConsent(true) before the OneSignal SDK gets fully initialized. Until this happens, you can continue to call methods (such as sendTags()), but nothing will happen.

OneSignal.setRequiresUserPrivacyConsent(true);
//to require the user's consent before the SDK initializes
OneSignal.setRequiresUserPrivacyConsent(true);
//to require the user's consent before the SDK initializes
[OneSignal setRequiresUserPrivacyConsent:true];
void YourAppInitMethod() {
  // SetRequiresUserPrivacyConsent will prevent
  //   initialization until UserDidProvideConsent(true) is called
  OneSignal.StartInit("YOUR_APP_ID")
    .SetRequiresUserPrivacyConsent(true)
    .EndInit();
}
// Will delay initialization of the SDK until the user provides consent
OneSignal.setRequiresUserPrivacyConsent(true);
await OneSignal.shared.setRequiresUserPrivacyConsent(true);
//will delay initialization of the SDK until the user provides consent
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.setRequiresUserPrivacyConsent(true);
//will delay initialization of the SDK
//make sure to call before init()
OneSignal.SetRequiresUserPrivacyConsent(true);

Consent Granted

If your application is set to require the user's privacy consent, you can provide this consent using this method. Until you call provideUserConsent(true), the SDK will not fully initialize, and will not send any data to OneSignal.

public void onUserTappedProvidePrivacyConsent(View v) {
  //will initialize the OneSignal SDK and enable push notifications
  OneSignal.provideUserConsent(true);
}
@IBAction func userTappedProvideConsentButton(_ sender : UIButton) {
  //this will complete the initialization of the SDK
    OneSignal.consentGranted(true); 
}
- (IBAction)setEmailButtonPressed:(UIButton *)sender {
  //this will complete the initialization of the SDK
  [OneSignal consentGranted:true];
}
void UserAcceptedConsent() {
   // Only needs to be called once,
   //   OneSignal will remember the last answer 
   OneSignal.UserDidProvideConsent(true);
}
function userTappedProvideConsentButton() {
  // Will initialize the SDK and register for push notifications
  OneSignal.provideUserConsent(true);
}
// the SDK will now initialize
await OneSignal.shared.consentGranted(true);
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.userProvidedPrivacyConsent((providedConsent) => {
  //if providedConsent == true, it means the SDK has been initialized and can be used
});
PrivacyConsentButton.TouchUpInside += delegate
{
  //the SDK will now be initialized
    OneSignal.UserDidProvidePrivacyConsent(true);
};

Location Data

setLocationShared Method

Disable or enable location collection (defaults to enabled if your app has location permission).

Note: This method must be called before OneSignal initWithLaunchOptions on iOS.

OneSignal.setLocationShared(false);
OneSignal.setLocationShared(false)
[OneSignal setLocationShared:false];
OneSignal.SetLocationShared(false);
OneSignal.setLocationShared(false);
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.setLocationShared(false)
await OneSignal.shared.setLocationShared(false);
OneSignal.SetLocationShared(false);
//Our Web SDK does not track location, you can setup the browser to track this and tag the user with the latitutde and longitude

isLocationShared Method

Return a boolean that indicates location shared state (defaults to true if your app has location permission).

boolean locationShared = OneSignal.isLocationShared();
let locationShared = OneSignal.isLocationShared()
BOOL locationShared = [OneSignal isLocationShared];
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.isLocationShared(function(shared) {
});

promptLocation Method

Recommended: use OneSignal's In-App Message Soft-Prompt before displaying the Native Alert. Details: Location Opt-In Prompt.

Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. This lets you send notifications based on the device's location. See Location-Triggered Notifications for more details.

Make sure you add location permissions in your AndroidManifest.xml and/or info.plist.

// Make sure you add one of the following permissions
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
//These are examples of how you may setup the app. See Apple's Guide on this: https://developer.apple.com/documentation/corelocation/requesting_authorization_for_location_services
// Example plist image: https://i.imgur.com/OZDQpyQ.png

<key>NSLocationUsageDescription</key>
  <string>Your message goes here</string>
<key>NSLocationWhenInUseUsageDescription</key>
    <string>Your message goes here</string>  
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
  <string>Your message goes here</string>
<key>NSLocationAlwaysUsageDescription</key>
    <string>Your message goes here</string>
<key>UIBackgroundModes</key>
    <array>
        <string>location</string>
        <string>remote-notification</string>
    </array>

On Android, you need to add the location dependency

dependencies {
  ...
  implementation 'com.google.android.gms:play-services-location:YOUR_PLAY_SERVICES_VERSION'
}

Finally, don't forget to call the prompt location method

OneSignal.promptLocation();
OneSignal.promptLocation()
[OneSignal promptLocation];
OneSignal.PromptLocation();
// Calling promptLocation
OneSignal.promptLocation();
await OneSignal.shared.promptLocationPermission();
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.promptLocation();
OneSignal.Current.PromptLocation();

Push Notifications

Notification Events & Payload

OneSignal Provides methods for handling notifications received and clicked/opened events. Details and discussion on implementation and Notification Payload in SDK Notification Event Handlers.

To send notifications to users, we recommend using the Create notification REST API docs, or Messages Dashboard.

postNotification Method

Recommended for scheduling notifications in the future to the current user.

🚧

User Targeting Warning

You can only use include_player_ids as a targeting parameter from your app. Other target options such as tags and included_segments require your OneSignal App REST API key which can only be used from your server.

See the Create notification REST API POST call for a list of all possible options.

Parameter

Type

Description

parameters

JSONObject, NSDictionary*, JSONString, Callback

Contains notification options, see our Create notification POST call for all options.

try {
  OneSignal.postNotification(new JSONObject("{'contents': {'en':'Test Message'}, 'include_player_ids': ['" + "userId" + "']}"),
     new OneSignal.PostNotificationResponseHandler() {
       @Override
       public void onSuccess(JSONObject response) {
         Log.i("OneSignalExample", "postNotification Success: " + response.toString());
       }

       @Override
       public void onFailure(JSONObject response) {
         Log.e("OneSignalExample", "postNotification Failure: " + response.toString());
       }
     });
} catch (JSONException e) {
  e.printStackTrace();
}
OneSignal.postNotification(["contents": ["en": "Test Message"], "include_player_ids": ["3009e210-3166-11e5-bc1b-db44eb02b120"]])
[OneSignal postNotification:@{
   @"contents" : @{@"en": @"Test Message"},
   @"include_player_ids": @[@"3009e210-3166-11e5-bc1b-db44eb02b120"]
}];
using OneSignalPush.MiniJSON;

private static string oneSignalDebugMessage;

void someMethod() {
// Just an example userId, use your own or get it the devices by using the GetPermissionSubscriptionState method
string userId = "b2f7f966-d8cc-11e4-bed1-df8f05be55ba";

var notification = new Dictionary<string, object>();
notification["contents"] = new Dictionary<string, string>() { {"en", "Test Message"} };

notification["include_player_ids"] = new List<string>() { userId };
// Example of scheduling a notification in the future.
notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U");

OneSignal.PostNotification(notification, (responseSuccess) => {
  oneSignalDebugMessage = "Notification posted successful! Delayed by about 30 secounds to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess);
}, (responseFailure) => {
  oneSignalDebugMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure);
});

}
const { userId } = await OneSignal.getDeviceState();

const notificationObj = {
  contents: {en: "Message Body"},
  include_player_ids: [userId]
};

const jsonString = JSON.stringify(notificationObj);

OneSignal.postNotification(jsonString, (success) => {
  console.log("Success:", success);
}, (error) => {
  console.log("Error:", error );
});
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.getIds(function(ids) {
  var notificationObj = { contents: {en: "message body"},
                          include_player_ids: [ids.userId]};
  window.plugins.OneSignal.postNotification(notificationObj,
    function(successResponse) {
      console.log("Notification Post Success:", successResponse);
    },
    function (failedResponse) {
      console.log("Notification Post Failed: ", failedResponse);
      alert("Notification Post Failed:\n" + JSON.stringify(failedResponse));
    }
  );
});
var status = await OneSignal.shared.getPermissionSubscriptionState();

var playerId = status.subscriptionStatus.userId;

await OneSignal.shared.postNotification(OSCreateNotification(
  playerIds: [playerId],
  content: "this is a test from OneSignal's Flutter SDK",
  heading: "Test Notification",
  send_after: DateTime.now().add(Duration(minutes: 30)).toUtc().toIso8601String();,
  buttons: [
    OSActionButton(text: "test1", id: "id1"),
    OSActionButton(text: "test2", id: "id2")
  ]
));
using OneSignalPush.MiniJSON;

private static string oneSignalDebugMessage;

void someMethod() {
// Just an example userId, use your own or get it the devices by calling OneSignal.GetIdsAvailable
string userId = "b2f7f966-d8cc-11e4-bed1-df8f05be55ba";

var notification = new Dictionary<string, object>();
notification["contents"] = new Dictionary<string, string>() { {"en", "Test Message"} };

notification["include_player_ids"] = new List<string>() { userId };
// Example of scheduling a notification in the future.
notification["send_after"] = System.DateTime.Now.ToUniversalTime().AddSeconds(30).ToString("U");

OneSignal.Current.PostNotification(notification, (responseSuccess) => {
  oneSignalDebugMessage = "Notification posted successful! Delayed by about 30 secounds to give you time to press the home button to see a notification vs an in-app alert.\n" + Json.Serialize(responseSuccess);
}, (responseFailure) => {
  oneSignalDebugMessage = "Notification failed to post:\n" + Json.Serialize(responseFailure);
});

}
function IdsAvailable(userID, pushToken)
    if (pushToken) then
        local notification = {
            ["contents"] = {["en"] = "test"}
        }
        notification["include_player_ids"] = {userID}
        
        OneSignal.PostNotification(notification,
            function(jsonData)
                native.showAlert( "DEBUG", "POST OK!!!", { "OK" } )
                local json = require "json"
                print(json.encode(jsonData))
            end,
            function(jsonData)
                native.showAlert( "DEBUG", "POST NOT OK!!!", { "OK" } )
                local json = require "json"
                print(json.encode(jsonData))
            end
        )
    end
end

OneSignal.IdsAvailableCallback(IdsAvailable)
OneSignal.sendSelfNotification(
  /* Title (defaults if unset) */
  "OneSignal Web Push Notification",
  /* Message (defaults if unset) */
  "Action buttons increase the ways your users can interact with your notification.", 
   /* URL (defaults if unset) */
  'https://example.com/?_osp=do_not_open',
  /* Icon */
  'https://onesignal.com/images/notification_logo.png',
  {
    /* Additional data hash */
    notificationType: 'news-feature'
  }, 
  [{ /* Buttons */
    /* Choose any unique identifier for your button. The ID of the clicked button is passed to you so you can identify which button is clicked */
    id: 'like-button',
    /* The text the button should display. Supports emojis. */
    text: 'Like',
    /* A valid publicly reachable URL to an icon. Keep this small because it's downloaded on each notification display. */
    icon: 'http://i.imgur.com/N8SN8ZS.png',
    /* The URL to open when this action button is clicked. See the sections below for special URLs that prevent opening any window. */
    url: 'https://example.com/?_osp=do_not_open'
  },
  {
    id: 'read-more-button',
    text: 'Read more',
    icon: 'http://i.imgur.com/MIxJp1L.png',
    url: 'https://example.com/?_osp=do_not_open'
  }]
);

clearOneSignalNotifications Method

Android only. iOS provides a standard way to clear notifications by clearing badge count. There is no specific OneSignal API call for clearing notifications.

OneSignal.clearOneSignalNotifications();
OneSignal.ClearOneSignalNotifications();
OneSignal.clearOneSignalNotifications();
//Currently not available
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
OneSignal.clearOneSignalNotifications();
OneSignal.Current.ClearOneSignalNotifications();
OneSignal.ClearAllNotifications()
//Not available

disablePush Method

The user must first subscribe through the native prompt or app settings. It does not officially subscribe or unsubscribe them from the app settings, it unsubscribes them from receiving push from OneSignal.
You can only call this method with true to opt out users from receiving notifications through OneSignal. You can pass false later to opt users back into notifications.

// Android SDK version 4.x.x
OneSignal.disablePush(true);

//Android SDK version 3.x.x
OneSignal.setSubscription(false);
// iOS SDK 3.x.x use
OneSignal.disablePush(true)

// iOS SDK 2.x.x use
OneSignal.setSubscription(false)
// iOS SDK 3.x.x use
[OneSignal disablePush:true];

// iOS SDK 2.x.x use
[OneSignal setSubscription:false];
//Coming soon, please use setSubscription for now. More details:
//https://documentation.onesignal.com/v7.0/docs/unity-sdk#setsubscription
OneSignal.SetSubscription(false);
// RN SDK 4.x.x use
OneSignal.disablePush(true);

// RN SDK 3.x.x use
OneSignal.setSubscription(false);
// Ionic 5 Capacitor may need to use (window as any).plugins.OneSignal
window.plugins.OneSignal.disablePush(false);
// Flutter SDK 3.x.x use
await OneSignal.shared.disablePush(true);

// Flutter SDK 2.x.x use
await OneSignal.shared.setSubscription(false);
OneSignal.SetSubscription(false);
OneSignal.SetSubscription(false)
OneSignal.setSubscription(false);

EnableVibrate & EnableSound Methods

These methods were designed for Android but stopped working in Android 8+ due to a breaking change. To customize going forward, use Android Notification Categories (Channels).

unsubscribeWhenNotificationsAreDisabled Method

Only available on Android Native SDK. If notifications are disabled for your app, unsubscribe the user from OneSignal.

Use case: if notifications are disabled for your app and you still want background notifications to work, pass in false.

OneSignal.unsubscribeWhenNotificationsAreDisabled(false);

In-App Messages

In-App Messages do not require any code to get started, but if you would like to setup custom triggers to display the In-App Message under certain conditions and track IAM lifecycle events, we have SDK methods for you!

See our In-App Message SDK Methods for details.


Email

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

See the Email SDK Methods guide for more details.

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an Email authentication token and send it to your app.


SMS

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

See the SMS SDK Methods guide for more details.

If you have a backend server, we strongly recommend using Identity Verification with your users. Your backend can generate an SMS authentication token and send it to your app.

Updated about a month ago



SDK Reference


Comprehensive reference of OneSignal's SDK methods

Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.