iOS Native - 3.0.0 API Changes
OneSignal iOS SDK Major Release Updates & Deprecations
New & Changed Methods
Reference | Details |
---|---|
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 onlydidReceiveNotificationExtensionRequest() | 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
initWithLaunchOptions
MethodParameter Type | Description |
---|---|
NSDictionary | Launch options from AppDelegate's didFinishLaunchingWithOptions |
setAppId
Method
setAppId
MethodSets the app id OneSignal should use in the application.
Parameter Type | Description |
---|---|
NSString | String app id associated with the OneSignal dashboard app. |
setLaunchURLsInApp
Method
setLaunchURLsInApp
MethodThis 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. |
Removed Methods
In version 3, there are several removed methods you should replace.
Removed Methods | Replacement |
---|---|
idsAvailable | Replaced by three observers: - addPermissionObserver - addSubscriptionObserver - addEmailSubscriptionObserver |
getPermissionSubscriptionState | Replaced by observers state observers: - addPermissionObserver - addSubscriptionObserver - addEmailSubscriptionObserver As well as getDeviceState |
presentAppSettings | Replaced by promptForPushNotificationsWithUserResponse:fallBackToSettings |
syncHashedEmail | No longer providing this functionality. Use setEmail instead. |
setNotificationDisplayType | Notification foreground display is now controlled using notificationWillShowInForegroundHandler. Note that the Alert notification display type has been removed. |
setSubscription | Replaced by disablePush |
kOSSettingsKeyAutoPrompt | Replaced by promptForPushNotificationsWithUserResponse:fallBackToSettings |
kOSSettingsKeyInAppLaunchURL | SDK 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 |
OSHandleNotificationReceivedBlock | Replaced by OSNotificationWillShowInForegroundBlock when notifications are received in the foreground andOSNotificationOpenedBlock 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
setNotificationWillShowInForegroundHandler
MethodRuns 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 | |
---|---|
OSNotificationWillShowInForegroundBlock | Block |
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:
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. |
Click/Open Handlers
OSHandleInAppMessageActionClickBlock
has been renamed to OSInAppMessageClickBlock
. It still takes an OSInAppMessageAction
parameter
OSInAppMessageAction
fields:
Type | Field | Description |
---|---|---|
NSString | clickName | An optional click name entered defined by the app developer when creating the IAM. |
NSURL | clickUrl | An optional URL that opens when the action takes place. |
BOOL | closesMessage | Determines if tapping on the element should close the In-App Message. |
BOOL | firstClick | Determines if this was the first action taken on the in app message. |
NSArray<OSInAppMessageOutcome *> | outcomes | Outcome for action. |
OSInAppMessagePrompt | prompts | Prompts for action. |
OSInAppMessageTag | tags | Tags for action. |
OSInAppMessageActionUrlType | urlTarget | Determines where the URL is opened, ie. |
setNotificationOpenedHandler
Method
setNotificationOpenedHandler
MethodParameter | |
---|---|
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:
Type | Field | Description |
---|---|---|
OSNotificationAction | action | The action the user took on the notification. |
OSNotification | notification | The 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
getDeviceState
MethodReturns 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
objectThis 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;
Type | Property | Description |
---|---|---|
NSString | userId | The Push Record Player ID. Null if called too early. |
BOOL | isSubscribed | Is device subscribed to push notifications. |
BOOL | hasNotificationPermission | Get the app's notification permission. |
Integer | notificationPermissionStatus | Current 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. |
NSString | pushToken | The device push token identifier. |
NSString | emailAddress | The user's email. |
NSString | emailUserId | The user's email id. |
BOOL | isPushDisabled | Returns the value of what was sent to OneSignal.disablePush(bool). False by default |
disablePush
Method
disablePush
MethodUse this method to opt users out of receiving all notifications through OneSignal.
Replaces: setSubscription
Parameter | |
---|---|
disabled | BOOL |
didReceiveNotificationExtensionRequest
Method
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.
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. |
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 |
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; |
Updated over 3 years ago