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

Xamarin SDK

📘

Just starting with Xamarin?

Check out our Xamarin SDK Setup guide.

ParameterData TypeDescription
Debugging
setLogLevelMethodEnable logging to help debug OneSignal implementation
Initialization
StartInitMethodStarts initialization of OneSignal, call this from your FinishedLaunching (iOS) or your OnCreate (Android) method. See Xamarin SDK Setup for code examples.
inFocusDisplayingMethodSetting to control how OneSignal notifications will be shown when one is received while your app is in focus.
SettingsMethodiOS - Automatically prompt users to enable notifications and open all URLs in In-App Safari window.
EndInitMethodMust be called after StartInit to complete initialization of OneSignal.
Handling Notifications
NotificationReceivedMethodWhen a notification is received by a device in the foreground.
HandleNotificationReceivedDelegate
NotificationOpenedMethodWhen a user takes an action on a notification.
HandleNotificationOpenedDelegate
Privacy
setRequiresUserPrivacyConsentMethodDelays initialization of the SDK until the user provides privacy consent
UserDidProvidePrivacyConsentMethodProvides privacy consent.
iOS Prompting
promptForPushNotificationsWithUserResponseMethodPrompt the user for notification permissions. Callback fires as soon as the user accepts or declines notifications.

Must set kOSSettingsKeyAutoPrompt to false when calling initWithLaunchOptions.

Recommended: Set to false and follow iOS Push Opt-In Prompt.
User Status
IdsAvailableCallbackDelegate
IdsAvailableMethodGet the user ID of the device.
setSubscriptionMethodDisable OneSignal from sending notifications to current device.
External User IDs
setExternalUserIdMethodAllows you to use your own system's user ID's to send push notifications to your users. To tie a user to a given user ID, you can use this method.
removeExternalUserIdMethodRemoves whatever was set as the current user's external user ID.
Tagging
getTagsMethodView Tags from current device record.
sendTagMethodAdd a single Data Tag to current device record.
sendTagsMethodAdd multiple Data Tags to current device record.
deleteTagMethodDelete a Tag from current device record.
deleteTagsMethodDelete multiple Tags from current device record.
Location Data
setLocationSharedMethodDisable or Enable SDK location collection. See Handling Personal Data.
promptLocationMethodPrompt Users for Location Not Recommended

Recommended: Use In-App Message Location Opt-In Prompt.
Sending Notifications
PostNotificationMethodSend or schedule a notification to a OneSignal Player ID.
CancelNotificationMethodDelete a single app notification.
ClearOneSignalNotificationsMethodDelete all app notifications.
In-App Messaging
addTriggerMethodAdd a trigger, may show an In-App Message if its triggers conditions were met.
addTriggersMethodAdd a map of triggers, may show an In-App Message if its triggers conditions were met.
removeTriggerForKeyMethodRemoves a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.
getTriggerValueForKeyMethodGets a trigger value for a provided trigger key.
pauseInAppMessagesMethodAllows you to temporarily pause all In App Messages.
setInAppMessageClickHandlerMethodSets an In App Message opened block
Email
setEmailMethodSet user's email. Creates a new user record for the email address. Use sendTag if you want to update a push user record with the email.
logoutEmailMethodLog user out to dissociate email from device
Notification Objects
OSNotificationOpenedResultClassInformation returned from a notification the user received.
OSNotificationClassRepresents a received push notification
OSNotificationActionClassHow user opened notification
OSNotificationPayloadClassData that comes with a notification.
Appearance
EnableVibrateMethodAndroid - When user receives notification, vibrate device less.
EnableSoundMethodAndroid - When user receives notification, do not play a sound.

Initialization

Settings

Method

Settings that can be passed into the initialization chaining method.

Settings key options are:

  • IOSSettings.kOSSettingsKeyAutoPrompt - Auto prompt user for notification permissions.
  • IOSSettings.kOSSettingsKeyInAppLaunchURL - Launch notifications with a launch URL as an in app webview.
ParameterTypeDescription
settingsDictionary<string, bool>Additional initialization settings. Set true or false.
OneSignal.Current.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba")
  .Settings(new Dictionary<string, bool>() {
    { IOSSettings.kOSSettingsKeyAutoPrompt, false },
    { IOSSettings.kOSSettingsKeyInAppLaunchURL, false } })
  .EndInit();

Privacy / GDPR

SetRequiresUserPrivacyConsent

Method

Allows you to delay the initialization of the SDK until the user provides privacy consent. The SDK will not be fully initialized until the UserDidProvidePrivacyConsent(true) method is called. Make sure to call this method before you initialize the SDK.

If you set this to be true, the SDK will not fully initialize until consent is provided. You can still call OneSignal methods, but nothing will happen, and the user will not be registered for push notifications.

//will delay initialization of the SDK
//make sure to call before init()
OneSignal.SetRequiresUserPrivacyConsent(true);

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 UserDidProvidePrivacyConsent(true) before the OneSignal SDK gets fully initialized. Until this happens, you can continue to call methods (such as SendTags()), but nothing will happen.

//will delay initialization of the SDK until the your application calls the method to provides consent.
OneSignal.Current.SetRequiresUserPrivacyConsent(true);

UserDidProvidePrivacyConsent

Method

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

PrivacyConsentButton.TouchUpInside += delegate
{
  //the SDK will now be initialized
    OneSignal.UserDidProvidePrivacyConsent(true);
};

For GDPR users, if you set the SDK to require the user's privacy consent, your application can use this method once the user does or doesn't provide privacy consent to use the OneSignal SDK.

public void userTappedProvideConsentButton() {
  //since the user agreed to your app's consent screen, provide consent with the SDK
  OneSignal.Current.UserDidProvidePrivacyConsent(true);
}

RequiresUserPrivacyConsent

Method

This method returns a boolean that indicates if the OneSignal SDK is waiting for the user to provide privacy consent.

  • true - Indicates that the OneSignal SDK hasn't received the user's privacy consent yet
  • false - Either the user has already provided consent, or your app isn't set to require consent.
if (OneSignal.Current.RequiresUserPrivacyConsent()) {
  // the SDK is waiting for your app to call UserDidProvidePrivacyConsent(true)
} else {
  // the user has provided consent and the SDK will initialize
}

Registering Push

RegisterForPushNotifications

Method - iOS

Call this when you would like to prompt an iOS user to accept push notifications with the default system prompt. Only use if you passed false to kOSSettingsKeyAutoPrompt when calling Init Settings.

OneSignal.Current.RegisterForPushNotifications();

User IDs

IdsAvailableCallback

Delegate

Delegate you can define to get the OneSignal userId and Google registration Id or an iOS push token.

ParameterTypeDescription
userIdStringOneSignal userId is a UUID formatted string. (unique per device per app)
pushTokenStringEither a Google registration Id or an iOS push token identifier(unique per device per app). NOTE: Might be blank if push notifications are not accepted on iOS, Google Play services are not installed, or from a connection issue.
private void IdsAvailable(string userID, string pushToken) {
        print("UserID:"  + userID);
        print("pushToken:" + pushToken);
    }

IdsAvailable

Method

Lets you retrieve the OneSignal player id and push token. Your delegate is called after the device is successfully registered with OneSignal. If the device has already successfully registered, the delegate will be called immediately.

ParameterTypeDescription
inIdsAvailableDelegateIdsAvailableCallbackCalls the delegate when the player id is available.
void SomeMethod() {
        OneSignal.Current.IdsAvailable(IdsAvailable);
    }

    private void IdsAvailable(string userID, string pushToken) {
        print("UserID:"  + userID);
        print("pushToken:" + pushToken);
    }

External IDs

setExternalUserId

Method

If your system assigns unique identifiers to users, it can be annoying to have to also remember their OneSignal user ID's as well. To make things easier, OneSignal now allows you to set an external_id for your users. Simply call this method, pass in your custom user ID (as a string), and from now on when you send a push notification, you can use include_external_user_ids instead of include_player_ids.

let myCustomUniqueUserId = "something from my backend server";

OneSignal.Current.SetExternalUserId(myCustomUniqueUserId);

removeExternalUserId

Method

If your user logs out of your app and you would like to disassociate their custom user ID from your system with their OneSignal user ID, you will want to call this method.

//usually called after the user logs out of your app
OneSignal.Current.RemoveExternalUserId()

Tags

GetTags

Method

Retrieve a list of tags that have been set on the player from the OneSignal server.

ParameterTypeDescription
inTagsReceivedDelegateTagsReceivedDelegate gets called once the tags are available.
void SomeMethod() {
        OneSignal.GetTags(TagsReceived);
    }

    private void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }

TagsReceived

Delegate

Delegate you can define to get the all the tags set on a player from onesignal.com.

ParameterTypeDescription
tagsDictionary<string, object>Dictionary of key value pairs retrieved from the OneSignal server.
private static void TagsReceived(Dictionary<string, object> tags) {
        foreach (var tag in tags)
            print(tag.Key + ":" + tag.Value);
    }

SendTag

Method

Tag a player based on a game event of your choosing so later you can create segments on onesignal.com to target these players. If you need to set more than one key at a time please use SendTags instead.

ParameterTypeDescription
keyStringKey of your choosing to create or update.
valueStringValue to set on the key. NOTE: Passing in a blank String deletes the key, you can also call DeleteTag or DeleteTags.
OneSignal.Current.SendTag("key", "value");

SendTags

Method

Set multiple tags on a player with one call.

ParameterTypeDescription
tagsDictionary<string, string>An IDictionary of key value pairs. NOTE: Passing in a blank as a value deletes the key, you can also call DeleteTag or DeleteTags.
OneSignal.Current.SendTags(new Dictionary<string, string>() { {"TestKey2", "value2"}, {"TestKey3", "value3"} });

DeleteTag

Method

Deletes a tag that was previously set on a player with SendTag or SendTags. Please use DeleteTags if you need to delete more than one tag.

ParameterTypeDescription
keyStringKey to remove.
OneSignal.DeleteTag("key");

DeleteTags

Method

Deletes tags that were previously set on a player with SendTag or SendTags.

ParameterTypeDescription
keysIListKeys to remove.
OneSignal.Current.DeleteTags(new List<string>() {"TestKey2", "TestKey3" })

Data

SetLocationShared

Method

Accepts a boolean parameter, allows you to enable or disable OneSignal SDK location tracking. Please note that if you disable location tracking, you will not be able to use location based push notifications.

//disables location features
OneSignal.SetLocationShared(false);

PromptLocation

Method

Prompts the user for location permissions. This allows for geotagging so you can send notifications to users based on location.

OneSignal.Current.PromptLocation();
iOS INSTRUCTIONS

You must add all of the following to your iOS plist settings:

NSLocationUsageDescription

NSLocationWhenInUseUsageDescription

ANDROID INSTRUCTIONS

You must add one of the following Android Permissions:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>


Sending Notifications

PostNotification

Method

Allows you to send notifications from user to user or schedule ones in the future to be delivered to the current device.

ParameterTypeDescription
parametersDictionary<string, object>Dictionary of notification options, see our Create notification POST call for all options.
ReturnsMethod
onSuccessOnPostNotificationSuccess delegate fires when the notification was created on OneSignal's server.

Dictionary<string, object> - Json response from OneSignal's server.
onFailureOnPostNotificationFailure delegate fires when the notification failed to create

Dictionary<string, object> - Json response from OneSignal's server.
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);
});

}

See the Create notification REST API POST call for a list of all possible options. Note: 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.

CancelNotification

Method - Android - *COMING SOON*

Deletes a single app notification.

ClearOneSignalNotifications

Method

Removes all OneSignal app notifications from the Notification Shade.

OneSignal.Current.ClearOneSignalNotifications();

SetSubscription

Method

You can call this method with false to opt users out of receiving all notifications through OneSignal. You can pass true later to opt users back into notifications.

ParameterType
enableBoolean
OneSignal.SetSubscription(false);

Receiving Notifications

NotificationReceived

Method

Use to process a OneSignal notification that is received when the app is running in the foreground or background.

ParameterTypeDescription
resultOSNotificationObject containing properties of the notification.
// Called when your app is in focus and a notificaiton is recieved.
// The name of the method can be anything as long as the signature matches.
// Method must be static or this object should be marked as DontDestroyOnLoad
private static void HandleNotificationReceived(OSNotification notification) {
  OSNotificationPayload payload = notification.payload;
  string message = payload.body;

  print("GameControllerExample:HandleNotificationReceived: " + message);
  print("displayType: " + notification.displayType);
  extraMessage = "Notification received with text: " + message;
}

HandleNotificationReceived

Delegate

Sets a notification received handler. The delegate will be called when a notification is received whether it was displayed or not when your app is in focus.

ParameterTypeDescription
handlerNotificationReceivedHandlerA delegate to handle the received event.
OneSignal.Current.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba")
  .HandleNotificationReceived(HandleNotificationReceived)
  .EndInit();

NotificationOpened

Method

Use to process a OneSignal notification the user just tapped on.

ParameterTypeDescription
resultOSNotificationOpenedResultObject containing both the user's response and properties of the notification.
// Called when a notification is opened.
// The name of the method can be anything as long as the signature matches.
// Method must be static or this object should be marked as DontDestroyOnLoad
private static void HandleNotificationOpened(OSNotificationOpenedResult result) {
  OSNotificationPayload payload = result.notification.payload;
  Dictionary<string, object> additionalData = payload.additionalData;
  string message = payload.body;
  string actionID = result.action.actionID;

  print("GameControllerExample:HandleNotificationOpened: " + message);
  extraMessage = "Notification opened with text: " + message;

  if (additionalData != null) {
    if (additionalData.ContainsKey("discount")) {
      extraMessage = (string)additionalData["discount"];
      // Take user to your store.
    }
  }
  if (actionID != null) {
    // actionSelected equals the id on the button the user pressed.
    // actionSelected will equal "__DEFAULT__" when the notification itself was tapped when buttons were present.
    extraMessage = "Pressed ButtonId: " + actionID;
  }
}
private static void HandleNotification(string message, Dictionary<string, object> additionalData, bool isActive) {
  bool hasButtons = (additionalData != null && additionalData.ContainsKey("actionSelected"));
  if (hasButtons) {
    if (additionalData["actionSelected"].Equals("id1"))
      print("button id1 pressed");
    else if (additionalData["actionSelected"].Equals("id2"))
      print("button id2 pressed");
    else if (additionalData["actionSelected"].Equals("__DEFAULT__"))
      print("Buttons present but you tapped on the notificaiton instead.");
  }
}
private static void HandleNotification(string message, Dictionary<string, object> additionalData, bool isActive) {
    print("Notification opned with Message: " + message);
    
    if (additionalData != null && additionalData.ContainsKey("stacked_notifications")) {
       var notificationsList = (List<object>)additionalData["stacked_notifications"];
       print("Stacked Sotification Opened, number on stack: " + notificationsList.Count);
       foreach (Dictionary<string, object> notifiAddData in notificationsList) {
          foreach (KeyValuePair<string, object> kvp in notifiAddData)
             print("Key = " + kvp.Key + ", Value = " + kvp.Value);
       }
    }
}

HandleNotificationOpened

Delegate

Delegate you can define to process information on the notification the user just opened.

ParameterTypeDescription
handlerNotificationReceivedHandlerA delegate to handle the open event.
OneSignal.Current.StartInit("b2f7f966-d8cc-11e4-bed1-df8f05be55ba")
  .HandleNotificationOpened(HandleNotificationOpened)
  .EndInit();

OSNotificationOpenedResult

Class

The information returned from a notification the user received.

ParameterTypeDescription
notificationOSNotificationNotification the user opened.
actionOSNotificationActionThe action the user took on the notification.

OSNotification

Class

The notification the user opened.

ParameterTypeDescription
isAppInFocusbooleanWas app in focus.
shownbooleanWas notification shown to the user. Will be false for silent notifications.
androidNotificationIdintAndroid Notification assigned to the notification. Can be used to cancel or replace the notification.
payloadOSNotificationPayloadPayload received from OneSignal.
displayTypeDisplayTypeHow the notification was displayed to the user.
groupedNotificationsList<OSNotificationPayload>Notification is a summary notification for a group this will contain all notification payloads it was created from.

displayType

Object

How the notification was displayed to the user. Part of OSNotification. See inFocusDisplaying for more information on how this is used.

  • Notification - native notification display.
  • InAppAlert (Default) - native alert dialog display (note this is not an In-App Message).
  • None - notification is silent, or inFocusDisplaying is disabled.

OSNotificationAction

Class

The action the user took on the notification.

ParameterTypeDescription
typeActionTypeWas the notification opened normally (Opened) or was a button pressed on the notification (ActionTaken).
actionIDStringIf type == ActionTaken then this will contain the id of the button pressed.

OSNotificationPayload

Class

Contents and settings of the notification the user received.

ParameterTypeDescription
notificationIdStringOneSignal notification UUID.
titleStringTitle of the notification.
bodyStringBody of the notification.
additionalDataDictionary<string, object>Custom additional data that was sent with the notification. Set on the dashboard under Options > Additional Data or with the 'data' field on the REST API.
smallIconStringSmall icon resource name set on the notification.
largeIconStringLarge icon set on the notification.
bigPictureStringBig picture image set on the notification.
smallIconAccentColorStringAccent color shown around small notification icon on Android 5+ devices. ARGB format.
launchUrlStringURL to open when opening the notification.
soundStringSound resource to play when the notification is shown.
ledColorStringDevices that have a notification LED will blink in this color. ARGB format.
lockScreenVisibilityintPrivacy setting for how the notification should be shown on the lockscreen of Android 5+ devices. 1 = Public (fully visible)(default), 0 = Private (Contents are hidden), -1 = Secret (not shown).
groupKeyStringNotifications with this same key will be grouped together as a single summary notification.
groupMessagestringSummary text displayed in the summary notification.
actionButtonsList<Dictionary<string, object>>List of action buttons on the notification.
fromProjectNumberStringThe Google project number the notification was sent under.
backgroundImageLayoutBackgroundImageLayoutIf a background image was set this object will be available.
rawPayloadStringRaw JSON payload string received from OneSignal.

ActionButton

Object

List of action buttons on the notification. Part of OSNotificationPayload.

ParameterTypeDescription
idStringId assigned to the button.
textStringText show on the button to the user.
iconStringIcon shown on the button.

BackgroundImageLayout

Object - Android

If a background image was set, this object will be available. Part of OSNotificationPayload.

ParameterTypeDescription
imageStringImage URL or name used as the background image.
titleTextColorStringText color of the title on the notification. ARGB Format.
bodyTextColorStringText color of the body on the notification. ARGB Format.

Appearance

EnableVibrate

Method - Android

By default OneSignal always vibrates the device when a notification is displayed unless the device is in a total silent mode. Passing false means that the device will only vibrate lightly when the device is in it's vibrate only mode.

You can link this action to a UI button to give your user a vibration option for your notifications.

OneSignal.Current.EnableVibrate(false);

EnableSound

Method - Android

By default OneSignal plays the system's default notification sound when the device's notification system volume is turned on. Passing false means that the device will only vibrate unless the device is set to a total silent mode.

You can link this action to a UI button to give your user a different sound option for your notifications.

OneSignal.Current.EnableSound(false);

In-App Messaging

Check out In-App Messaging Quickstart to get an overview before diving into the SDK methods below.

In-App - Triggers

Triggers are something you fire in your app based on events/state changes which may show an In-App Message. Every time you add or remove a trigger with the below methods the SDK will evaluate if an In-App Message should be shown based on the Trigger conditions set on it via OneSignal Dashboard when it was created.

Triggers are reset each time your app is closed so make sure to set them again when starting your app if you need any of them to be persistent.

AddTrigger

Method

Add a trigger, may show an In-App Message if its triggers conditions were met.

ParameterTypeDescription
keyStringKey for the trigger
valueObjectValue for the trigger.
Object passed in will have toString() called if not a String
OneSignal.Current.AddTrigger("trigger_1", "one");

AddTriggers

Method

Add a map of triggers, may show an In-App Message if its triggers conditions were met.

ParameterTypeDescription
triggersDictionary<string, object>Allows you to set multiple trigger key/value pairs simultaneously
Dictionary<string, object> triggers = new Dictionary<string, object>();
triggers.Add("trigger_2", "two");
triggers.Add("trigger_3", "three");
OneSignal.Current.AddTriggers(triggers);

RemoveTriggerForKey

Method

Removes a single trigger for the given key, may show an In-App Message if its triggers conditions were met.

ParameterTypeDescription
keyStringKey for trigger to remove
OneSignal.Current.RemoveTriggerForKey("trigger_2");

RemoveTriggersForKeys

Method

Removes a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met.

ParameterTypeDescription
keysList<String>Removes a collection of triggers from their keys
List<string> removeKeys = new List<string>();
removeKeys.Add("trigger_1");
removeKeys.Add("trigger_3");
OneSignal.Current.RemoveTriggersForKeys(removeKeys);

GetTriggerValueForKey

Method

Gets a trigger value for a provided trigger key.

ParameterTypeDescription
keyStringReturns a single trigger value for the given key,
if it exists, otherwise returns null
Return TypeDescription
objectValue if added with AddTrigger or null if never set.
object value = OneSignal.Current.GetTriggerValueForKey("trigger_1");
Debug.WriteLine("trigger_1 value: " + value);

In App - Misc

PauseInAppMessages

Method

Allows you to temporarily pause all In-App Messages. You may want to do this while the user is watching a video playing a match in your game to make sure they don't get interrupted at a bad time.

ParameterTypeDescription
pausebooleanTo pause set true
To resume set false

In App - Handlers

HandleInAppMessageClicked

Builder Method

Sets a In App Message opened handler. The instance will be called when an In App Message action is tapped on.

ParameterTypeDescription
handlerDelegateInstance to a class implementing this interference.

Example

OneSignal.Current.StartInit("b0f7f966-d8ec-11e4-bed1-df8f05je55ba").Settings(new Dictionary<string, bool>() {
            { IOSSettings.kOSSettingsKeyAutoPrompt, false },
            { IOSSettings.kOSSettingsKeyInAppLaunchURL, true } })
           .HandleInAppMessageClicked((action) =>
           {
              // Example IAM click handling for IAM elements
              Debug.WriteLine("HandledInAppMessageClicked: {0}", action.clickName);
           })
           .EndInit();

OSInAppMessageAction

Class

Details about the In-App Message action element (button or image) that was tapped on. Passed into the delegate for HandleInAppMessageClicked.

FieldTypeDescription
clickNameStringAn optional click name defined for the action element.
null if not set
clickUrlStringAn optional URL that opens when the action takes place.
null if not set.
firstClickbooleantrue if this is the first time the user has pressed
any action on the In App Message.
closesMessagebooleanDid the action close the In App Message.
true the In App Message will animate off the screen.
false the In App Message will stay on screen until the user dismisses.

Email

SetEmail

Method

SetEmail allows you to set the user's email address with the OneSignal SDK. We offer several overloaded versions of this method.

The user's email will be cached by our SDK, so it is only necessary to call this method a single time.

Note: Because several events must occur before the SDK can set the user's email with our API, please note that the callbacks for SetEmail may take several seconds, and in the very worst-case can take up to 30 seconds.

OneSignal.Current.SetEmail("[email protected]");

// Optionally, you can also use callbacks
OneSignal.Current.SetEmail("[email protected]", () => {
  //handle success
}, (error) => {
  //handle failure
});

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. The following code also includes callbacks:

string email = "[email protected]";
string emailAuthCode = ; //generated on your backend server
OneSignal.SetEmail(email, emailAuthCode);

// Optionally, you can also use callbacks
OneSignal.Current.SetEmail(email, emailAuthCode, () => {
    //handle success
}, (error) => {
    //handle failure
});

LogoutEmail

Method

If your app implements logout functionality, you can call LogoutEmail to dissociate the email from the device:

OneSignal.Current.LogoutEmail();

// Optionally, you can also use callbacks
OneSignal.Current.LogoutEmail(() => {
  //handle success
}, (error) => {
  //handle failure
});

Updated 3 months ago


Xamarin SDK


Suggested Edits are limited on API Reference Pages

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