iOS Native SDK 2.x.x

OneSignal iOS Native API Reference

🚧

Deprecated OneSignal-iOS-SDK 2.x.x version

This is for the older 2.x.x version of the API. Please see the latest API reference here

ParameterData TypeDescription
Debugging
setLogLevelMethodEnable logging to help debug OneSignal implementation
Initialization
initWithLaunchOptionsMethodInitialize OneSignal
inFocusDisplayTypePropertySetting to control how OneSignal notifications will be shown when one is received while your app is in focus.
Settings
kOSSettingsKeyAutoPromptKeyAutomatically Prompt Users to Enable Notifications. See iOS SDK Setup for code examples.

true (Default) - automatically prompts for notifications permissions.

false - disables auto prompt.

Recommended: Set to false and follow iOS Push Opt-In Prompt.
kOSSettingsKeyInAppLaunchURLKeyOpen URLs in In-App Safari Window or Safari app. See iOS SDK Setup for code examples.

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).
Handling Notifications
handleNotificationReceivedMethodCalled when the app receives a notification while in focus only.
handleNotificationActionMethodCalled when the user opens or taps an action on a notification.
Privacy
setRequiresUserPrivacyConsentMethodDelays initialization of the SDK until the user provides privacy consent
consentGrantedMethodTells the SDK that the user has provided privacy consent (if required)
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.
presentAppSettingsMethodPresents the iOS Settings for your application
User StatusMore Details
getPermissionSubscriptionStateMethodGet the current notification and permission state. Returns a OSPermissionSubscriptionState type.
addPermissionObserverMethodObserver method for Current Device Record's Permission status changes.
addSubscriptionObserverMethodObserver method for Current Device Record's Subscription status changes.
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.
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
addEmailSubscriptionObserverMethodObserver for subscription changes to email
Notification Objects
OSNotificationOpenedResultObjectInformation returned from a notification the user received.
OSNotificationObjectRepresents a received push notification
OSNotificationActionObjectHow user opened notification
OSNotificationPayloadObjectData that comes with a notification

Initialization

initWithLaunchOptions

Method

Must be called from didFinishLaunchingWithOptions in AppDelegate.m.

ParameterTypeDescription
launchOptionsNSDictionary*Required launchOptions that you received from didFinishLaunchingWithOptions
appIdNSString*Required Your OneSignal app id, available in Keys & IDs
callbackOSHandleNotificationReceivedBlockFunction to be called when a notification is received
callbackOSHandleNotificationActionBlockFunction to be called when a user reacts to a notification received
settingsNSDictionary*Customization settings to change OneSignal's default behavior
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: false]

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

   OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification

   return true
}
- (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];
  
}

Handling 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 limited due to iOS restrictions.

ParameterTypeDescription
notificationOSNotificationThe OneSignal Notification Object
let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { 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.

ParameterTypeDescription
resultOSNotificationOpenedResultData available within the OneSignal Notification Object when clicking the notification.
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"])"
      }
   }
}
^(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);
action(OSNotificationAction);

OSNotification

Interface Element

The notification the user received.

Class Properties
payload(OSNotificationPayload);
displayType(OSNotificationDisplayType);
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.
type(OSNotificationActionType);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 PropertiesRaw Value
Notification2iOS native notification display.
InAppAlert1Default UIAlertView display (note this is not an In-App Message)
None0Notification 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
parseWithApns (Method);Parses an APS push payload into a OSNotificationPayload object. Useful to call from your NotificationServiceExtension when the didReceiveNotificationRequest:withContentHandler: method fires.

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. This method will open the iOS Settings page for your app that they can then select notifications option to enable them.

❗️

Deprecation Warning

presentAppSettings is deprecated in OneSignal iOS SDK Major Release 3.0+

Use promptForPushNotifications with fallbackToSettings set to true instead.

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

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.

ParameterTypeDescription
parametersNSDictionary*Dictionary of notification options, see our Create notification POST call for all options.
onSuccess(Optional)OneSignalResultSuccessBlockCalled if there were no errors sending the notification
onFailure(Optional)OneSignalFailureBlockCalled 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.