iOS Native SDK

OneSignal iOS Native API Reference

📘

Just starting with iOS?

Check out our iOS SDK Setup guide.

📘

Latest API

This page is for the latest 3.0.0 version of the API, released Dec. 9, 2020.

Still using the 2.x.x version?

ParameterData TypeDescription
Debugging
setLogLevelMethodEnable logging to help debug OneSignal implementation
Initialization
initWithLaunchOptionsMethodInitializes OneSignal.
You should call from your AppDelegate's didFinishLaunchingWithOptions.
You must also call OneSignal.setAppId to finish initialization.
setAppIdMethodCall this to set or change the OneSignal appId required for initialization.
Handling Notifications
setNotificationWillShowInForegroundHandlerMethodCalled when the app receives a notification while in focus only.
setNotificationOpenedHandlerMethodCalled 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.
promptForPushNotificationsWithUserResponse:fallbackToSettings:MethodPrompt the user for notification permissions. Use the fallbackToSettings parameter to prompt to open the settings app if a user has already declined push permissions
User Status
getDeviceStateMethodReturns an OSDeviceState object with device info.
addPermissionObserverMethodObserver method for Current Device Record's Permission status changes.
addSubscriptionObserverMethodObserver method for Current Device Record's Subscription status changes.
disablePushMethodDisable 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.
isLocationSharedMethodReturns a boolean that indicates if location is shared
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.
clearAllNotificationsDocumentationAll Notifications cleared when badges are cleared
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
Misc
setLaunchURLsInAppMethodSet to true to launch all notifications with a URL in the app instead of the default web browser.
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

Initialization is a two step process requiring both initWithLaunchOptions and setAppId to be called. Note that you can call setAppId at any point in your app's flow. This allows full initialization to be delayed until say, a user logs in.

Must be called from didFinishLaunchingWithOptions in AppDelegate.m / AppDelegate.swift.

ParameterTypeDescription
launchOptionsNSDictionary*Required launchOptions that you received from didFinishLaunchingWithOptions
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  // OneSignal initialization
  OneSignal.initWithLaunchOptions(launchOptions)
  OneSignal.setAppId("YOUR_ONESIGNAL_APP_ID")
}
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions {
    [OneSignal initWithLaunchOptions:launchOptions];
    [OneSignal setAppId:@"########-####-####-####-############"];
}

setAppId

Sets the app id OneSignal should use in the application.

Parameter TypeDescription
NSStringString app id associated with the OneSignal dashboard app.

Handling Notifications

setNotificationWillShowInForegroundHandler

Callback

Runs before displaying a notification while the app is in focus. Use this handler to decide if the notification should show or not. To silence the notification pass nil to the completion handler and to show the notification pass the notification to the completion handler. If the completion handler is not called within 25 seconds the notification will be shown.

Note: this runs after the Notification Service Extension which can be used to modify the notification content before showing it.

ParameterTypeDescription
OSNotificationWillShowInForegroundBlockBlockCall to block to complete the event

The block is provided with an OSNotification instance and a completion block.

let notifWillShowInForegroundHandler: OSNotificationWillShowInForegroundBlock = { notification, completion in
    print("Received Notification: ", notification.notificationId ?? "no id")
    print("launchURL: ", notification.launchURL ?? "no launch url")
    print("content_available = \(notification.contentAvailable)")
    if notification.notificationId == "example_silent_notif" {
        completion(nil)
    } else {
        completion(notification)
    }
}
id notifWillShowInForegroundHandler = ^(OSNotification *notification, OSNotificationDisplayResponse completion) {
        NSLog(@"Received Notification - %@", notification.notificationId);
        if ([notification.notificationId isEqualToString:@"silent_notif"]) {
            completion(nil);
        } else {
            completion(notification);
        }
    };

[OneSignal setNotificationWillShowInForegroundHandler:notifWillShowInForegroundHandler];

setNotificationOpenedHandler

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: OSNotificationOpenedBlock = { result in
    // This block gets called when the user reacts to a notification received
    let notification: OSNotification = result.notification
    print("Message: ", notification.body ?? "empty body")
    print("badge number: ", notification.badge)
    print("notification sound: ", notification.sound ?? "No sound")
            
    if let additionalData = notification.additionalData {
        print("additionalData: ", additionalData)
        if let actionSelected = notification.actionButtons {
            print("actionSelected: ", actionSelected)
        }
        if let actionID = result.action.actionId {
            //handle the action
        }
    }
}
id notificationOpenedBlock = ^(OSNotificationOpenedResult *result) {
  OSNotification* notification = result.notification;
  if (notification.additionalData) {
    if (result.action.actionId) {
      fullMessage = [fullMessage stringByAppendingString:[NSString stringWithFormat:@"\nPressed ButtonId:%@", result.action.actionId]];
    }
  }

OSNotificationOpenedResult

Interface Element

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

TypeFieldDescription
OSNotificationnotificationThe notification the user received.
OSNotificationActionactionThe action the user took on the notification.

OSNotification

Interface Element
TypeProperty/MethodDescription
NSStringnotificationId OneSignal notification UUID.
NSStringtitleThe message title.
NSStringsubtitleThe message subtitle.
NSStringbodyThe message body.
NSStringtemplateIdUnique Template Identifier
NSStringtemplateNameName of Template
NSStringlaunchURLWeb address to launch within the app via WKWebView
NSStringcategoryNotification category key previously registered to display with.
NSStringthreadIdiOS 10+ only. Groups notifications into threads
NSDictionaryattachmentsiOS 10+ only. Attachments sent as part of the rich notification
NSDictionaryadditionalDataAdditional key value properties set within the payload.
BOOLcontentAvailableTrue when the key content-available is set to 1 in the APNS payload. Used to wake your app when the payload is received.

See Apple's documenation for more details.
BOOLmutableContentTrue when the key mutable-content is set to 1 in the APNS payload.

See Apple's documenation for more details.
NSIntegerbadgeThe badge number assigned to the application icon.
NSIntegerbadgeIncrementThe amount to increment the badge icon number.
NSArrayactionButtonsAction buttons set on the notification.
NSDictionaryrawPayloadHolds the raw APS payload received.
MethodparseWithApnsParses an APS push payload into a OSNotificationPayload object. Useful to call from your NotificationServiceExtension when the didReceiveNotificationRequest:withContentHandler: method fires.

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

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

getDeviceState

Returns an OSDeviceState object with device info.

OSDeviceState

if let deviceState = OneSignal.getDeviceState() {
    let userId = deviceState.userId
    let pushToken = deviceState.pushToken
    let subscribed = deviceState.isSubscribed
 }
OSDeviceState *deviceState = [OneSignal getDeviceState];
NSString *userId = deviceState.userId;
NSString *pushToken = deviceState.pushToken;
BOOL subscribed = deviceState.isSubscribed;
TypePropertyDescription
NSStringuserIdThe OneSignal player / user id
NSStringpushTokenThe device iOS push token
BOOLhasNotificationPermissionGet the app's notification permission.
BOOLisSubscribedWhether the user is subscribed for OneSignal Push notifications
BOOLisPushDisabledReturns the value of what was sent to OneSignal.disablePush(bool).
False by default
NSStringemailAddressThe user's email.
NSStringemailUserIdThe user's email id.
OSNotificationPermissionnotificationPermissionStatusAn enumeration representing the current notification permission state.

disablePush

Use this method to opt users out of receiving all notifications through OneSignal.

ParameterType
disabledBOOL

setLaunchURLsInApp

This method can be used to set if launch URLs should be opened in safari or within the application

Parameter TypeDescription
BoolBoolean indicating if launch URLs should be opened in safari or within the application.

clearAllNotifications

All Notifications are cleared when your badge count is set to 0. Thus there is no specific OneSignal API call for clearing notifications.


Notification Service Extension

The notification service extension is used to add rich media to your notifications and change its content before being displayed to the user. OneSignal handles all of this for you by calling the following function from didReceiveNotificationRequest

didReceiveNotificationExtensionRequest

ParameterTypeDescription
requestUNNotificationRequestThe request that is passed into the native function
replacementContentUNMutableNotificationContentThe content of the request retrieved through [request.content mutableCopy]. Any non-OneSignal changes that you want to make to the notification should be made to the content before passing the content to this method.
SDK version 3.5.0 and higher only
contentHandler
contentHandler callbackThe contentHandler completion block that triggers the display of the notification. Prior to SDK 3.5.0 you should call contentHandler(<UNMutableNotificationContent>) with the new request content to trigger the notification's display. As of 3.5.0 this is handled automatically by passing the contentHandler to didReceiveNotificationExtensionRequest