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?
- See our Mobile SDKs API Migration Guides to get updated to the latest SDK.
- If you can't upgrade yet? See the API 2.x.x reference.
Parameter | Data Type | Description |
---|---|---|
Debugging | ||
setLogLevel | Method | Enable logging to help debug OneSignal implementation |
Initialization | ||
initWithLaunchOptions | Method | Initializes OneSignal. You should call from your AppDelegate's didFinishLaunchingWithOptions .You must also call OneSignal.setAppId to finish initialization. |
setAppId | Method | Call this to set or change the OneSignal appId required for initialization. |
Handling Notifications | ||
setNotificationWillShowInForegroundHandler | Method | Called when the app receives a notification while in focus only. |
setNotificationOpenedHandler | Method | Called when the user opens or taps an action on a notification. |
Privacy | ||
setRequiresUserPrivacyConsent | Method | Delays initialization of the SDK until the user provides privacy consent |
consentGranted | Method | Tells the SDK that the user has provided privacy consent (if required) |
iOS Prompting | ||
promptForPushNotificationsWithUserResponse | Method | Prompt the user for notification permissions. Callback fires as soon as the user accepts or declines notifications. |
promptForPushNotificationsWithUserResponse:fallbackToSettings: | Method | Prompt 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 | ||
getDeviceState | Method | Returns an OSDeviceState object with device info. |
addPermissionObserver | Method | Observer method for Current Device Record's Permission status changes. |
addSubscriptionObserver | Method | Observer method for Current Device Record's Subscription status changes. |
disablePush | Method | Disable OneSignal from sending notifications to current device. |
External User IDs | ||
setExternalUserId | 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. |
removeExternalUserId | Method | Removes whatever was set as the current user's external user ID. |
Tagging | ||
getTags | Method | View Tags from current device record. |
sendTag | Method | Add a single Data Tag to current device record. |
sendTags | Method | Add multiple Data Tags to current device record. |
deleteTag | Method | Delete a Tag from current device record. |
deleteTags | Method | Delete multiple Tags from current device record. |
Location Data | ||
setLocationShared | Method | Disable or Enable SDK location collection. See Handling Personal Data. |
isLocationShared | Method | Returns a boolean that indicates if location is shared |
promptLocation | Method | Prompt Users for Location Not Recommended Recommended: Use In-App Message Location Opt-In Prompt. |
Sending Notifications | ||
postNotification | Method | Send or schedule a notification to a OneSignal Player ID. |
clearAllNotifications | Documentation | All Notifications cleared when badges are cleared |
In-App Messaging | ||
addTrigger | Method | Add a trigger, may show an In-App Message if its triggers conditions were met. |
addTriggers | Method | Add a map of triggers, may show an In-App Message if its triggers conditions were met. |
removeTriggerForKey | Method | Removes a list of triggers based on a collection of keys, may show an In-App Message if its triggers conditions were met. |
getTriggerValueForKey | Method | Gets a trigger value for a provided trigger key. |
pauseInAppMessages | Method | Allows you to temporarily pause all In App Messages. |
setInAppMessageClickHandler | Method | Sets an In App Message opened block |
setEmail | Method | Set 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. |
logoutEmail | Method | Log user out to dissociate email from device |
addEmailSubscriptionObserver | Method | Observer for subscription changes to email |
Misc | ||
setLaunchURLsInApp | Method | Set to true to launch all notifications with a URL in the app instead of the default web browser. |
Notification Objects | ||
OSNotificationOpenedResult | Object | Information returned from a notification the user received. |
OSNotification | Object | Represents a received push notification |
OSNotificationAction | Object | How user opened notification |
OSNotificationPayload | Object | Data that comes with a notification |
Initialization
initWithLaunchOptions
initWithLaunchOptions
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
.
Parameter | Type | Description |
---|---|---|
launchOptions | NSDictionary* | 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
setAppId
Sets the app id OneSignal should use in the application.
Parameter Type | Description |
---|---|
NSString | String app id associated with the OneSignal dashboard app. |
Handling Notifications
setNotificationWillShowInForegroundHandler
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.
Parameter | Type | Description |
---|---|---|
OSNotificationWillShowInForegroundBlock | Block | Call 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
setNotificationOpenedHandler
Called when the user opens or taps an action on a notification.
Parameter | Type | Description |
---|---|---|
result | OSNotificationOpenedResult | Data 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
OSNotificationOpenedResult
The information returned from a notification the user received. Resulting class passed to OSHandleNotificationActionBlock.
Type | Field | Description |
---|---|---|
OSNotification | notification | The notification the user received. |
OSNotificationAction | action | The action the user took on the notification. |
OSNotification
OSNotification
Type | Property/Method | Description |
---|---|---|
NSString | notificationId | OneSignal notification UUID. |
NSString | title | The message title. |
NSString | subtitle | The message subtitle. |
NSString | body | The message body. |
NSString | templateId | Unique Template Identifier |
NSString | templateName | Name of Template |
NSString | launchURL | Web address to launch within the app via WKWebView |
NSString | category | Notification category key previously registered to display with. |
NSString | threadId | iOS 10+ only. Groups notifications into threads |
NSDictionary | attachments | iOS 10+ only. Attachments sent as part of the rich notification |
NSDictionary | additionalData | Additional key value properties set within the payload. |
BOOL | contentAvailable | True 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. |
BOOL | mutableContent | True when the key mutable-content is set to 1 in the APNS payload. See Apple's documenation for more details. |
NSInteger | badge | The badge number assigned to the application icon. |
NSInteger | badgeIncrement | The amount to increment the badge icon number. |
NSArray | actionButtons | Action buttons set on the notification. |
NSDictionary | rawPayload | Holds the raw APS payload received. |
Method | parseWithApns | Parses an APS push payload into a OSNotificationPayload object. Useful to call from your NotificationServiceExtension when the didReceiveNotificationRequest:withContentHandler: method fires. |
OSNotificationAction
OSNotificationAction
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
OSNotificationActionType
The action type (NSUInteger Enum) associated to an OSNotificationAction object.
NSUInteger Enum Properties |
---|
Opened |
ActionTaken |
Sending Notifications
postNotification
postNotification
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"]
}];
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;
Type | Property | Description |
---|---|---|
NSString | userId | The OneSignal player / user id |
NSString | pushToken | The device iOS push token |
BOOL | hasNotificationPermission | Get the app's notification permission. |
BOOL | isSubscribed | Whether the user is subscribed for OneSignal Push notifications |
BOOL | isPushDisabled | Returns the value of what was sent to OneSignal.disablePush(bool). False by default |
NSString | emailAddress | The user's email. |
NSString | emailUserId | The user's email id. |
OSNotificationPermission | notificationPermissionStatus | An enumeration representing the current notification permission state. |
disablePush
Use this method to opt users out of receiving all notifications through OneSignal.
Parameter | Type |
---|---|
disabled | BOOL |
setLaunchURLsInApp
This method can be used to set if launch URLs should be opened in safari or within the application
Parameter Type | Description |
---|---|
Bool | Boolean 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
Parameter | Type | Description |
---|---|---|
request | UNNotificationRequest | The request that is passed into the native function |
replacementContent | UNMutableNotificationContent | The 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 callback | The 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 |
Updated almost 2 years ago