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

iOS Native SDK

OneSignal iOS Native SDK Reference

For Developers

Just starting with iOS?

Check out our iOS SDK Setup guide.

Initialization

Method

Initialize OneSignal

Privacy

Method

Determines whether the SDK should delay initialization

Method

Provides privacy consent

Boolean

Indicates if the SDK is waiting for the user's privacy consent

Settings

Key

Automatically Prompt Users to Enable Notifications

Key

Open URLs in In-App Safari Window or Safari app

Property

Changes how notifications display while in the app

Prompting

Method

Prompt Users to Enable Notifications

Method

Presents the iOS Settings for your application

Status

Method

Current Permission and Subscription status

Method

Permission status changes

Method

Subscription status changes

Tags

Method

View Tags from a User

Method

Add a Tag to a User

Method

Method

Delete a Tag from a User

Method

Data

Method

Disable or Enable SDK location collection

Method

Prompt Users for Location

Automatic

Get In-App Purchase Information

Sending Notifications

Method

Send or schedule a notification to a user

Method

Delete all app notifications

Method

Opt users in or out of receiving notifications

Email

Method

Set user's email

Method

Log user out to dissociate email from device

Method

Observer for subscription changes to email

External ID's

Method

Allows 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.

Method

Removes whatever was set as the current user's external user ID.

Notification Events

Method

When a notification is received by a device.

Method

When a user takes an action on a notification

Objects

Object

How user opened notification

Object

Change how notifications are displayed to users

Object

Data that comes with a notification

Debug

Method

Enable logging to help debug OneSignal implementation

Initialization

initWithLaunchOptions

Method

Must be called from didFinishLaunchingWithOptions in AppDelegate.m.

Parameter
Type
Description

launchOptions

NSDictionary*

Required launchOptions that you received from didFinishLaunchingWithOptions

appId

NSString*

Required Your OneSignal app id, available in Keys & IDs

callback

Function to be called when a notification is received

callback

Function to be called when a user reacts to a notification received

settings

NSDictionary*

Customization settings to change OneSignal's default behavior

iOS 8+ Notes

  • application:didRegisterForRemoteNotificationsWithDeviceToken: will still fire even if kOSSettingsKeyAutoPrompt is set to false.
  • Replace any of your isRegisteredForRemoteNotifications calls with currentUserNotificationSettings or getPermissionSubscriptionState.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

   let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in

      print("Received Notification: \(notification!.payload.notificationID)")
   }

   let notificationOpenedBlock: OSHandleNotificationActionBlock = { result in
      // This block gets called when the user reacts to a notification received
      let payload: OSNotificationPayload = result!.notification.payload

      var fullMessage = payload.body
      print("Message = \(fullMessage)")

      if payload.additionalData != nil {
         if payload.title != nil {
            let messageTitle = payload.title
               print("Message Title = \(messageTitle!)")
         }

         let additionalData = payload.additionalData
         if additionalData?["actionSelected"] != nil {
            fullMessage = fullMessage! + "\nPressed ButtonID: \(additionalData!["actionSelected"])"
         }
      }
   }

   let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false,
      kOSSettingsKeyInAppLaunchURL: true]

   OneSignal.initWithLaunchOptions(launchOptions, 
      appId: "YOUR_ONESIGNAL_APP_ID", 
      handleNotificationReceived: notificationReceivedBlock, 
      handleNotificationAction: notificationOpenedBlock, 
      settings: onesignalInitSettings)

   OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification

   return true
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

OneSignal.initWithLaunchOptions(launchOptions, appId: "YOUR_ONESIGNAL_APP_ID", handleNotificationReceived: { (notification) in
                print("Received Notification - \(notification.payload.notificationID)")
            }, handleNotificationAction: { (result) in
                
                // This block gets called when the user reacts to a notification received
                let payload = result.notification.payload
                var fullMessage = payload.title
                
                //Try to fetch the action selected
                if let additionalData = payload.additionalData, actionSelected = additionalData["actionSelected"] as? String {
                    fullMessage =  fullMessage + "\nPressed ButtonId:\(actionSelected)"
                }
                print(fullMessage)
            }, settings: [kOSSettingsKeyAutoPrompt : true, kOSSettingsKeyInFocusDisplayOption : OSNotificationDisplayType.notification.rawValue])

}
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
 
  id notificationReceiverBlock = ^(OSNotification *notification) {
    NSLog(@"Received Notification - %@", notification.payload.notificationID);
  };
  
  id notificationOpenedBlock = ^(OSNotificationOpenedResult *result) {
        // This block gets called when the user reacts to a notification received
        OSNotificationPayload* payload = result.notification.payload;
        
        NSString* messageTitle = @"OneSignal Example";
        NSString* fullMessage = [payload.body copy];
        
        if (payload.additionalData) {
            
            if(payload.title)
                messageTitle = payload.title;
            
            NSDictionary* additionalData = payload.additionalData;
            
            if (additionalData[@"actionSelected"])
                fullMessage = [fullMessage stringByAppendingString:[NSString stringWithFormat:@"\nPressed ButtonId:%@", additionalData[@"actionSelected"]]];
        }
        
        UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:messageTitle
                                                            message:fullMessage
                                                           delegate:self
                                                  cancelButtonTitle:@"Close"
                                                  otherButtonTitles:nil, nil];
        [alertView show];

   };
  
   id onesignalInitSettings = @{kOSSettingsKeyAutoPrompt : @YES};
  
   [OneSignal initWithLaunchOptions:launchOptions
                              appId:@"YOUR_ONESIGNAL_APP_ID"
         handleNotificationReceived:notificationReceiverBlock
           handleNotificationAction:notificationOpenedBlock
                           settings:onesignalInitSettings];
  
}

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.


//to require the user's consent before the SDK initializes
OneSignal.setRequiresUserPrivacyConsent(true);

OneSignal.initWithLaunchOptions(launchOptions, appId: "YOUR_ONESIGNAL_APP_ID");
//to require the user's consent before the SDK initializes
[OneSignal setRequiresUserPrivacyConsent:true];

[OneSignal initWithLaunchOptions:launchOptions appId:@"YOUR_ONESIGNAL_APP_ID"];

consentGranted

Method

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.

@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];
}

requiresUserPrivacyConsent

Boolean

You can use this property to check 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.

kOSSettingsKeyAutoPrompt

Key

true (Default) - automatically prompts for notifications permissions.
false - disables auto prompt.

kOSSettingsKeyInAppLaunchURL

Key

true (Default) - Open all URLs with a in-app WebView window.
false - Launches Safari with the URL OR other app (if deep linked or custom URL scheme passed).

inFocusDisplayType

Property

Setting to control how app notifications will be shown when one is received while your app is in focus, for apps targeting.

Note: this setting will affect all push notifications for your app (regardless if from OneSignal or another service)

Objective C format:
OSNotificationDisplayTypeNotification - Native notification display
OSNotificationDisplayTypeInAppAlert (Default) - Alert dialog display.
OSNotificationDisplayTypeNone - Notification is silent and not shown

Swift format:
OSNotificationDisplayType.notification
OSNotificationDisplayType.inAppAlert
OSNotificationDisplayType.none

OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification
OneSignal.inFocusDisplayType = OSNotificationDisplayTypeNotification;

iOS 9 AND BELOW - the Notification setting will fall back to InAppAlert .

Registering Push

promptForPushNotificationsWithUserResponse

Method

Prompt the user for notification permissions. Callback fires as soon as the user accepts or declines notifications.

Requirements

Must set kOSSettingsKeyAutoPrompt to false when calling initWithLaunchOptions.

Recommendations

You can only prompt once so it is recommend to explain what benefits notifications will give the user.

Example

// Call when you want to prompt the user to accept push notifications. 
// Only call once and only if you set kOSSettingsKeyAutoPrompt in AppDelegate to false.
OneSignal.promptForPushNotifications(userResponse: { accepted in
   print("User accepted notifications: \(accepted)")
})
[OneSignal promptForPushNotificationsWithUserResponse:^(BOOL accepted) {
  NSLog(@"Accepted Notifications?: %d", accepted);
}];

presentAppSettings

Method

iOS does not allow you to prompt for push notification permissions a second time if the user has denied it the first time. However, you can put a Notifications Enabled UISwitch in your app and if they change their mind, you can open the iOS Settings page for your app that will enable them to turn on notifications.

// will open iOS Settings for your app
OneSignal.presentAppSettings()
[OneSignal presentAppSettings];

getPermissionSubscriptionState

Method

Get the current notification and permission state. Returns a OSPermissionSubscriptionState type described below.

OSPermissionSubscriptionState

Parameter
Type
Description

permissionStatus

OSPermissionState*

iOS Notification Permissions state

subscriptionStatus

OSSubscriptionState*

Apple and OneSignal subscription state

let status: OSPermissionSubscriptionState = OneSignal.getPermissionSubscriptionState()

let hasPrompted = status.permissionStatus.hasPrompted
print("hasPrompted = \(hasPrompted)")
let userStatus = status.permissionStatus.status
print("userStatus = \(userStatus)")

let isSubscribed = status.subscriptionStatus.subscribed
print("isSubscribed = \(isSubscribed)")
let userSubscriptionSetting = status.subscriptionStatus.userSubscriptionSetting
print("userSubscriptionSetting = \(userSubscriptionSetting)")
let userID = status.subscriptionStatus.userId
print("userID = \(userID)")
let pushToken = status.subscriptionStatus.pushToken
print("pushToken = \(pushToken)")
OSPermissionSubscriptionState* status = [OneSignal getPermissionSubscriptionState];
status.permissionStatus.hasPrompted;
status.permissionStatus.status;
    
status.subscriptionStatus.subscribed;
status.subscriptionStatus.userSubscriptionSetting;
status.subscriptionStatus.userId;
status.subscriptionStatus.pushToken;

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

Example

Example of setting up with your AppDelegate.
Output is showings the user accepting the notification permission prompt.

// 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

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 Apple
  • Getting a player / user id from OneSignal
  • OneSignal.setSubscription is called
  • User disables or enables notifications

Example

Example of setting up with your AppDelegate. Output is showing the capture the device subscribing to OneSignal.

// 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

Advanced Observer Details

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.

getTags

Method

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

Parameter
Type
Description

successBlock

OneSignalResultSuccessBlock

Called when tags are received from OneSignal's server

onFailure(Optional)

OneSignalFailureBlock

Called if there was an error.

OneSignal.getTags({ tags in
	print("tags - \(tags!)")
}, onFailure: { error in
	print("Error getting tags - \(error?.localizedDescription)")
})
oneSignal.getTags({ (tags) in
	print("%@", tags)
}, { (error) in
   print("Error getting tags - \(error.localizedDescription)")
})
[oneSignal getTags:^(NSDictionary* tags) {
	NSLog(@"%@", tags);
}];

sendTag

Method

Tag a user based on an app event of your choosing so later you can create segments on onesignal.com to target these users. Recommend using sendTags over sendTag if you need to set more than one tag on a user at a time.

Parameter
Type
Description

key

NSString*

Key of your choosing to create or update

value

NSString*

Value to set on the key. NOTE: Passing in a blank String deletes the key, you can also call deleteTag or deleteTags.

onSuccess(Optional)

OneSignalResultSuccessBlock

Call if there were no errors sending the tag

onFailure(Optional)

OneSignalFailureBlock

Called if there was an error

OneSignal.sendTag("key", value: "value")
[OneSignal sendTag:@"key" value:@"value"];

sendTags

Method

Tag a user based on an app event of your choosing so later you can create segments on onesignal.com to target these users.

Parameter
Type
Description

keyValues

NSDictionary*

Key value pairs of your choosing to create or update. NOTE: Passing in a blank NSString* as a value deletes the key, you can also call deleteTag or deleteTags.

onSuccess(Optional)

OneSignalResultSuccessBlock

Call if there were no errors sending the tag

onFailure(Optional)

OneSignalFailureBlock

Called if there was an error

OneSignal.sendTags(["key1": "value1", "key2": "value2"])
[OneSignal sendTags:@{@"key1" : @"value1", @"key2" : @"value2"}];

deleteTag

Method

Deletes a single tag that was previously set on a user with sendTag or sendTags. Use deleteTags if you need to delete more than one.

Parameter
Type
Description

key

NSString*

Key to remove

onSuccess(Optional)

OneSignalResultSuccessBlock

Call if there were no errors

onFailure(Optional)

OneSignalFailureBlock

Called if there was an error

OneSignal.deleteTag("key")
[OneSignal deleteTag:@"key"];

deleteTags

Method

Deletes one or more tags that were previously set on a user with sendTag or sendTags.

Parameter
Type
Description

keys

NSArray*

Keys to remove

onSuccess(Optional)

OneSignalResultSuccessBlock

Call if there were no errors

onFailure(Optional)

OneSignalFailureBlock

Called if there was an error

OneSignal.deleteTags(["key1", "key2"])
[OneSignal deleteTags:@[@"key1", @"key2"]];

Data

setLocationShared

Method

Allows you to enable or disable OneSignal SDK location collection. Due to Apple's App Store Guidelines, it is required in iOS applications to get the user's consent before collecting location.

promptLocation

Method

Prompts the user for location permissions to allow geotagging from the OneSignal dashboard. This lets you send notifications based on the device's location.

Note: Requires the follow entries in your .plist file.

  • NSLocationUsageDescription (For iOS 7 and later)
  • NSLocationWhenInUseUsageDescription
    Optional:
  • NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationAlwaysUsageDescription along with UIBackgroundModes -> location
    Example plist image: https://i.imgur.com/OZDQpyQ.png
OneSignal.promptLocation()
[OneSignal promptLocation];

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.

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.

Parameter
Type
Description

parameters

NSDictionary*

Dictionary of notification options, see our Create notification POST call for all options.

onSuccess(Optional)

OneSignalResultSuccessBlock

Called if there were no errors sending the notification

onFailure(Optional)

OneSignalFailureBlock

Called if there was an error

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

ClearOneSignalNotifications

Method

iOS provides a standard way to clear notifications by clearing badge count, thus there is no specific OneSignal API call for clearing notifications.

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.

Parameter
Type
Description

enable

BOOL

OneSignal.setSubscription(false)
[OneSignal setSubscription:false];

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.

OneSignal.setEmail("example@domain.com");
[OneSignal setEmail:@"example@domain.com"];

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:

let emailAuthHash = //generated on your backend server
let email = "example@domain.com";
OneSignal.setEmail(email, withEmailAuthHashToken: emailAuthHash, withSuccess: {
    //The email has successfully been set.
}) { (error) in
    //Encountered an error while setting the email.
};
NSString *hashToken = //hash token from your server
NSString *emailAddress = @"example@domain.com";
[OneSignal setEmail:emailAddress withEmailAuthHashToken:hashToken onSuccess: ^() {
    //The email has successfully been set.
} onFailure: ^(NSError *error) {
    //Encountered an error while setting the email.
}];

logoutEmail

Method

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

OneSignal.logoutEmail();
[OneSignal logoutEmail];

addEmailSubscriptionObserver

Method

We have also added a new email subscription observer to track changes to email subscriptions (ie. the user sets their email or logs out). In order to subscribe to email subscription changes you can implement the following:

OneSignal.add(self as OSEmailSubscriptionObserver)
[OneSignal addEmailSubscriptionObserver:self];

Now, whenever the email subscription changes, this method will be called:

func onOSEmailSubscriptionChanged(_ stateChanges: OSEmailSubscriptionStateChanges!) { 
    
}
-(void)onOSEmailSubscriptionChanged:(OSEmailSubscriptionStateChanges *)stateChanges {
    
}

External User ID's

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.setExternalUserId(myCustomUniqueUserId)
NSString *myCustomUniqueUserId = @"something from my backend server";

[OneSignal 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.removeExternalUserId()

//usually called after the user logs out of your app
[OneSignal removeExternalUserId];

Receiving Notifications

OSHandleNotificationReceivedBlock

Callback

Called when the app receives a notification while in focus only. Note: If you need this to be called when your app is in the background, set content_available to true when you create your notification. The "force-quit" state (i.e app was swiped away) is not currently supported.

Parameter
Type
Description

notification

{ notification in
	print("Received Notification - \(notification.payload.notificationID) - \(notification.payload.title)")
}
^(OSNotification *notification) {
	NSLog(@"Received Notification - %@ - %@", notification.payload.notificationID, notification.payload.title);
}

OSHandleNotificationActionBlock

Callback

Called when the user opens or taps an action on a notification.

Parameter
Type
Description
{ result in
                
	// This block gets called when the user reacts to a notification received
	let payload: OSNotificationPayload = result!.notification.payload
	var fullMessage = payload.body
                
	//Try to fetch the action selected
	if let additionalData = payload.additionalData, actionSelected = additionalData["actionSelected"] as? String {
		fullMessage =  fullMessage + "\nPressed ButtonId:\(actionSelected)"
	}
	print("fullMessage = \(fullMessage)")
}
^(OSNotificationOpenedResult *result) {
        
   // This block gets called when the user opens or taps an action on a notification
   OSNotificationPayload* payload = result.notification.payload;
        
   NSString* messageTitle = @"OneSignal Example";
   NSString* fullMessage = [payload.body copy];
        
   if (payload.additionalData) {
      if (payload.title)
         messageTitle = payload.title;
            
      NSDictionary* additionalData = payload.additionalData;
            
      if (additionalData[@"actionSelected"])
         fullMessage = [fullMessage stringByAppendingString:[NSString stringWithFormat:@"\nPressed ButtonId:%@", additionalData[@"actionSelected"]]];
   }
  
   UIAlertView* alertView = [[UIAlertView alloc]
                               initWithTitle:messageTitle
                                     message:fullMessage
                                    delegate:self
                           cancelButtonTitle:@"Close"
                          otherButtonTitles:nil, nil];
   [alertView show];
}

OSNotificationOpenedResult

Interface Element

The information returned from a notification the user received. Resulting class passed to OSHandleNotificationActionBlock.

Class Properties

notification(OSNotification);

OSNotification

Interface Element

The notification the user received.

Class Properties

shown(BOOL);

True when the user was able to see the notification. False when app is in focus and in-app alerts are disabled, or the remote notification is silent.

silentNotification(BOOL);

True when the received notification is silent. Silent means there is no alert, sound, or badge payload in the APS dictionary. Requires remote-notification within UIBackgroundModes array of the Info.plist

OSNotificationAction

Interface Element

The action the user took on the notification.

Class Properties

actionID(NSString);

The ID associated with the button tapped. NULL when the actionType is NotificationTapped or InAppAlertClosed.

The type of the notification action.

OSNotificationActionType

Interface Element

The action type (NSUInteger Enum) associated to an OSNotificationAction object.

NSUInteger Enum Properties

Opened

ActionTaken

OSNotificationDisplayType

Interface Element

The way in which a notification was displayed to the user (NSUInteger Enum).

NSUInteger Enum Properties
Raw Value

Notification

2

iOS native notification display.

InAppAlert

1

Default UIAlertView display.

None

0

Notification is silent, or app is in focus but InAppAlertNotifications are disabled.

OSNotificationPayload

Interface Element

Contents and settings of the notification the user received.

Class Properties

notificationID (NSString);

OneSignal notification UUID

contentAvailable(BOOL);

Provide this key with a value of 1 to indicate that new content is available. Including this key and value means that when your app is launched in the background or resumed application:didReceiveRemoteNotification:fetchCompletionHandler: is called.

badge(NSInteger);

The badge number assigned to the application icon

sound(NSString);

The sound parameter passed to the notification. By default set to UILocalNotificationDefaultSoundName. Read more about custom sounds

title(NSString);

Title text of the notification

body (NSString);

Body text of the notification

subtitle (NSString);

iOS 10+ - subtitle text of the notification

launchURL(NSString);

Web address to launch within the app via a UIWebView

additionalData(NSDictionary);

Additional Data add to the notification by you

attachments(NSDictionary);

iOS 10+ - Attachments sent as part of the rich notification

actionButtons(NSArray);

Action buttons set on the notification

rawPayload(NSDictionary);

Holds the raw APS payload received

Debug

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. 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.

Parameters
Type
Description

logLevel

LOG_LEVEL

Sets the logging level to print to the Xcode log

visualLevel

LOG_LEVEL

Sets the logging level to show as alert dialogs.

OneSignal.setLogLevel(.LL_DEBUG, visualLevel: .LL_DEBUG)
[OneSignal setLogLevel:ONE_S_LL_DEBUG visualLevel:ONE_S_LL_DEBUG];

iOS Native SDK


OneSignal iOS Native SDK Reference

For Developers

Suggested Edits are limited on API Reference Pages

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