iOS Native - 3.0.0 API Changes

OneSignal iOS SDK Major Release Updates & Deprecations

New & Changed Methods

ReferenceDetails
initWithLaunchOptions()1/2 of initialization process. Now only takes launchOptions as an argument.
setAppId()1/2 of initialization process. Sets the OneSignal app id.
setLaunchURLsInApp()Set to true to launch all notifications with a URL in an In App WebView
getDeviceState()Gets information about the device.
disablePush()Use this method to opt users out of receiving all notifications through OneSignal.
Replaces: setSubscription
setNotificationWillShowInForegroundHandler() Use this method to handle notifications received in the foreground. For silent notifications use the Notification Service Extension. Replaces: OSHandleNotificationReceivedBlock
Versions 3.5.0 and higher only
didReceiveNotificationExtensionRequest()
This method now takes the contentHandler completion block and calls it. You no longer need to call contentHandler(bestAttemptContent) after calling this method in didReceiveNotificationRequest. Any non-OneSignal changes to the notification content should be made before calling this method.

Initialization

In version 3, initialization is now 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.

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

initWithLaunchOptions Method

Parameter TypeDescription
NSDictionaryLaunch options from AppDelegate's didFinishLaunchingWithOptions

setAppId Method

Sets the app id OneSignal should use in the application.

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

setLaunchURLsInApp Method

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.

Removed Methods

❗️

In version 3, there are several removed methods you should replace.

Removed MethodsReplacement
idsAvailableReplaced by three observers:

- addPermissionObserver
- addSubscriptionObserver
- addEmailSubscriptionObserver
getPermissionSubscriptionStateReplaced by observers state observers:

- addPermissionObserver
- addSubscriptionObserver
- addEmailSubscriptionObserver

As well as getDeviceState
presentAppSettingsReplaced by promptForPushNotificationsWithUserResponse:fallBackToSettings
syncHashedEmailNo longer providing this functionality. Use setEmail instead.
setNotificationDisplayTypeNotification foreground display is now controlled using notificationWillShowInForegroundHandler.
Note that the Alert notification display type has been removed.
setSubscriptionReplaced by disablePush
kOSSettingsKeyAutoPromptReplaced by promptForPushNotificationsWithUserResponse:fallBackToSettings
kOSSettingsKeyInAppLaunchURLSDK version 3.2.1+
Replaced by setting OneSignal_suppress_launch_urls in the Info.plist
- YES will not show the launch url in an in-app browser.
- NO will show the launch url in an in-app browser.
Example Suppress Launch URLs
OSHandleNotificationReceivedBlockReplaced by OSNotificationWillShowInForegroundBlock when notifications are received in the foreground and
OSNotificationOpenedBlock
when notifications are tapped

New Methods

Foreground Notification Control

In version 3, you can now specifically read notification data that will display while the app is in focus as well as change the display type dynamically. This allows developers to have even greater control over the notification experience.

setNotificationWillShowInForegroundHandler Method

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
OSNotificationWillShowInForegroundBlockBlock

The block replaces the OSHandleNotificationReceivedBlock and is provided with an OSNotification instance and a completion block. OSNotificationPayload has been removed and combined with OSNotification.

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

OneSignal.setNotificationWillShowInForegroundHandler(notifWillShowInForegroundHandler)
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];

OSNotification properties:

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.

Click/Open Handlers

OSHandleInAppMessageActionClickBlock has been renamed to OSInAppMessageClickBlock. It still takes an OSInAppMessageAction parameter

OSInAppMessageAction fields:

TypeFieldDescription
NSString clickNameAn optional click name entered defined by the app developer when creating the IAM.
NSURL clickUrlAn optional URL that opens when the action takes place.
BOOL closesMessageDetermines if tapping on the element should close the In-App Message.
BOOL firstClickDetermines if this was the first action taken on the in app message.
NSArray<OSInAppMessageOutcome *>outcomesOutcome for action.
OSInAppMessagePromptpromptsPrompts for action.
OSInAppMessageTagtagsTags for action.
OSInAppMessageActionUrlTypeurlTargetDetermines where the URL is opened, ie.

setNotificationOpenedHandler Method

Parameter
OSNotificationOpenedBlock Block

This block was renamed from OSHandleNotificationActionBlock to OSNotificationOpenedBlock. It is provided with a result object of type OSNotificationOpenedResult.

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

OneSignal.setNotificationOpenedHandler(notificationOpenedBlock)
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]];
    }
  }
  
[OneSignal setNotificationOpenedHandler:notificationOpenedBlock];

OSNotificationOpenResult fields:

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

Go to OSNotification reference.

OSNotificationActionType Enum:
The action type associated to an OSNotificationAction object.

Value
OSNotificationActionTypeOpened
OSNotificationActionTypeActionTaken

OSNotificationAction property actionID has been renamed to actionId.:


Other Methods

getDeviceState Method

Returns an OSDeviceState object with device info. This method can be used in place of getPermissionSubscriptionState to get information on the current subscription statuses for all messaging channels on demand. To be notified of status changes use the OSPermissionObserver, OSSubscriptionObserver, OSEmailSubscriptionObserver, and OSSMSSubscriptionObserver.

🚧

Do not cache OSDeviceState object

This method returns a "snapshot" of the device state for when it was called. To ensure fresh state, make sure to call getDeviceState each time you need to get one of the member fields.

OSDeviceState getters:

if let deviceState = OneSignal.getDeviceState() {
    let userId = deviceState.userId
    print("OneSignal Push Player ID: ", userId ?? "called too early, not set yet")
    let subscribed = deviceState.isSubscribed
    print("Device is subscribed: ", subscribed)
    let hasNotificationPermission = deviceState.hasNotificationPermission
    print("Device has notification permissions enabled: ", hasNotificationPermission)
    let notificationPermissionStatus = deviceState.notificationPermissionStatus
    print("Device's notification permission status: ", notificationPermissionStatus.rawValue)
    let pushToken = deviceState.pushToken
    print("Device Push Token Identifier: ", pushToken ?? "no push token, not subscribed")
}
OSDeviceState *deviceState = [OneSignal getDeviceState];
NSString *userId = deviceState.userId;
NSString *pushToken = deviceState.pushToken;
BOOL subscribed = deviceState.isSubscribed;
TypePropertyDescription
NSStringuserIdThe Push Record Player ID. Null if called too early.
BOOLisSubscribedIs device subscribed to push notifications.
BOOLhasNotificationPermissionGet the app's notification permission.
IntegernotificationPermissionStatusCurrent notification permission status of the device.

0 - "NotDetermined" - The user hasn't yet made a choice about whether the app is allowed to schedule notifications.

1 - "Denied" - The app isn't authorized to schedule or receive notifications.

2 - "Authorized" - The app is authorized to schedule or receive notifications.

3 - "Provisional" - The application is provisionally authorized to post noninterruptive user notifications. See iOS Customizations

4 - "Ephemeral" - For App Clips. The app is authorized to schedule or receive notifications for a limited amount of time.
NSStringpushTokenThe device push token identifier.
NSStringemailAddressThe user's email.
NSStringemailUserIdThe user's email id.
BOOLisPushDisabledReturns the value of what was sent to OneSignal.disablePush(bool).
False by default

disablePush Method

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

Parameter
disabledBOOL

didReceiveNotificationExtensionRequest Method

Versions 3.5.0 and higher only
This method now takes the contentHandler completion block and calls it. You no longer need to call contentHandler(bestAttemptContent) after calling this method in didReceiveNotificationRequest. Any non-OneSignal changes to the notification content should be made before calling this method.

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

Other Changes

app_id has been renamed to appId
sdk_version_raw has been renamed to sdkVersionRaw
sdk_semantic_version has been renamed to sdkSemanticVersion

Nullability for Swift interface

Nullability annotations have been added to the OneSignal header to make the Swift interface easier to use.
Xcode will point these changes out as warning or errors to help you migrate however below outlines the changes.

func onOSPermissionChanged(_ stateChanges: OSPermissionStateChanges)
func onOSPermissionChanged(_ stateChanges: OSPermissionStateChanges!)
New Nonnull Annotations
Methods- deleteTag
- deleteTags
- deleteTagsWithJsonString
- didReceiveNotificationExtensionRequest
- getTags
- handleMessageAction
- onOSEmailSubscriptionChanged
- onOSPermissionChanged
- onOSSubscriptionChanged
- onesignal_Log
- parseNSErrorAsJsonString
- postNotification
- postNotification
- postNotificationWithJsonString
- sdkSemanticVersion
- sdkVersionRaw
- stringify
- sendTag
- sendTags
- sendTagsWithJsonString
- serviceExtensionTimeWillExpireRequest
- setMSDKType
- toDictionary
Properties- OSNotificationAction *action
- OSNotification* notification
- OSNotificationPayload* payload
New Nullable Annotations
Methods- didReceiveNotificationExtensionRequest
- serviceExtensionTimeWillExpireRequest
- setInAppMessageClickHandler
- setLaunchOptions
- setNotificationOpenedHandler
- setNotificationWillShowInForegroundHandler
onSuccess & onFailure Block Parameters- deleteTag
- deleteTags
- getTag
- getTags
- sendTags
- postNotification
- postNotificationWithJsonString
- sendOutcomeWithValue
Properties- OSEmailSubscriptionState *emailSubscriptionStatus;
- OSEmailSubscriptionState* from;
- OSEmailSubscriptionState* to;
- OSPermissionState* from;
- OSPermissionState* permissionStatus;
- OSPermissionState* to;
- OSSubscriptionState* from;
- OSSubscriptionState* subscriptionStatus;
- OSSubscriptionState* to;
- NSDictionary* attachments;
- NSString *threadId;
- NSString* actionID;
- NSString* body;
- NSString* category;
- NSString* launchURL;
- NSString* notificationID;
- NSString* sound;
- NSString* subtitle;
- NSString* templateID;
- NSString* templateName;
- NSString *title;
- NSString *emailAddress;
- NSString* emailUserId;
- NSString* pushToken;
- NSString* userId;