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
Parameter | Data Type | Description |
---|---|---|
Debugging | ||
setLogLevel | Method | Enable logging to help debug OneSignal implementation |
Initialization | ||
initWithLaunchOptions | Method | Initialize OneSignal |
inFocusDisplayType | Property | Setting to control how OneSignal notifications will be shown when one is received while your app is in focus. |
Settings | ||
kOSSettingsKeyAutoPrompt | Key | Automatically 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. |
kOSSettingsKeyInAppLaunchURL | Key | Open 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 | ||
handleNotificationReceived | Method | Called when the app receives a notification while in focus only. |
handleNotificationAction | 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. Must set kOSSettingsKeyAutoPrompt to false when calling initWithLaunchOptions.Recommended: Set to false and follow iOS Push Opt-In Prompt. |
presentAppSettings | Method | Presents the iOS Settings for your application |
User Status | More Details | |
getPermissionSubscriptionState | Method | Get the current notification and permission state. Returns a OSPermissionSubscriptionState type. |
addPermissionObserver | Method | Observer method for Current Device Record's Permission status changes. |
addSubscriptionObserver | Method | Observer method for Current Device Record's Subscription status changes. |
setSubscription | 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. |
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. |
clearOneSignalNotifications | Method | Delete all app notifications |
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 |
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
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 | OSHandleNotificationReceivedBlock | Function to be called when a notification is received |
callback | OSHandleNotificationActionBlock | Function to be called when a user reacts to a notification received |
settings | NSDictionary* | 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
OSHandleNotificationReceivedBlock
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.
Parameter | Type | Description |
---|---|---|
notification | OSNotification | The 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
OSHandleNotificationActionBlock
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: 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
OSNotificationOpenedResult
The information returned from a notification the user received. Resulting class passed to OSHandleNotificationActionBlock.
Class Properties |
---|
notification (OSNotification); |
action (OSNotificationAction); |
OSNotification
OSNotification
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
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 or InAppAlertClosed. |
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 |
OSNotificationDisplayType
OSNotificationDisplayType
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 (note this is not an In-App Message) |
None | 0 | Notification is silent, or app is in focus but InAppAlertNotifications are disabled. |
OSNotificationPayload
OSNotificationPayload
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
presentAppSettings
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
withfallbackToSettings
set to true instead.
// will open iOS Settings for your app
OneSignal.presentAppSettings()
[OneSignal presentAppSettings];
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"]
}];
ClearOneSignalNotifications
ClearOneSignalNotifications
iOS provides a standard way to clear notifications by clearing badge count, thus there is no specific OneSignal API call for clearing notifications.
Updated over 2 years ago