iOS SDK Reference
Complete API reference for the PushEngage iOS SDK. For setup and installation, see the iOS Quickstart.
The SDK supports Swift, Objective-C, and SwiftUI applications. iOS 10.0+ is required.
Initialization
swizzleInjection
This method automates the setup process of the SDK through method swizzling. If developers prefer not to handle the SDK setup manually, calling this method in the init method of the Application AppDelegate is essential. Method swizzling allows the SDK to perform necessary configurations without explicit manual intervention.
Syntax
swizzleInjection(isEnabled: Bool)
Parameters
isEnabled: A boolean value indicating whether to enable the SDK setup through method swizzling.
- Set to
trueto enable automatic SDK configuration using method swizzling. - Set to
falseto require manual setup configuration.
Usage
Automated Setup -
PushEngage.swizzleInjection(isEnabled: true)
Manual Setup -
PushEngage.swizzleInjection(isEnabled: false)
setAppID
Call this method in the AppDelegate to set the app push ID in the SDK, registering the subscriber to that specific app push ID.
Syntax
setAppID(id: String)
Parameters
id: A String representing the app push ID to be set.
- This ID uniquely identifies the app in the push notification service.
- Must be a valid app push ID provided by PushEngage.
Usage
PushEngage.setAppID(id: "YOUR_APP_PUSH_ID")
setEnvironment
Set the environment for the SDK, allowing developers to switch between staging and production environments.
Syntax
setEnvironment(environment: PEEnvironment)
Parameters
environment: An enum value of type PEEnvironment representing the desired environment to be set.
- Use
.stagingfor development and testing purposes. - Use
.productionfor live app deployments.
Usage
PushEngage.setEnvironment(environment: .staging)
setInitialInfo
Provide necessary prerequisite information to the SDK for internal setup.
Syntax
setInitialInfo(for application: UIApplication, with launchOptions: [UIApplication.LaunchOptionsKey: Any]?)
Parameters
application: An instance of UIApplication representing the host application.
launchOptions: A dictionary of launch options passed to the application during launch.
Usage
PushEngage.setInitialInfo(for: UIApplication.shared, with: launchOptions)
registerDeviceToServer
Register Device Token Manually.
Use this method to manually register the device token with the PushEngage server if swizzling is not used.
Syntax
registerDeviceToServer(with deviceToken: Data)
Parameters
deviceToken: The device token obtained from Apple Push Notification service (APNs) as Data.
- This token uniquely identifies the app installation on the device.
- Required for sending push notifications to this specific device.
Usage
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
PushEngage.registerDeviceToServer(with: deviceToken)
}
Notification Permission
requestNotificationPermission
Show prompt to user asking for notification permission.
Syntax
requestNotificationPermission(completion: @escaping (_ response: Bool, _ error: Error?) -> Void)
Parameters
completion: A closure that gets called with the result of the permission request.
isGranted: A boolean indicating the permission result.- Will be
trueif notification permission was granted by the user. - Will be
falseif notification permission was denied by the user.
- Will be
error: An optional Error object that contains details if the permission request failed.- Will be
nilif the operation completed successfully.
- Will be
Returns
Delivered asynchronously via completion closure:
isGranted(Bool):trueif notification permission was granted.error(Error?): An error object if the request failed,nilotherwise.
Usage
PushEngage.requestNotificationPermission { isGranted, error in
if isGranted {
print("Notification permission granted successfully.")
return
}
if let error = error {
print("Failed to get notification permission: \(error.localizedDescription)")
} else {
print("Notification permission denied by user.")
}
}
getNotificationPermissionStatus
Get the current notification permission status for the application. This method returns the permission status synchronously as a string.
Syntax
getNotificationPermissionStatus() -> String
Returns
A String indicating the current notification permission state:
"granted": The application is authorized to post user notifications"denied": The application is not authorized to post user notifications"notYetRequested": The user has not yet made a choice regarding notification permissions
Usage
let permissionStatus = PushEngage.getNotificationPermissionStatus()
switch permissionStatus {
case "granted":
print("Notifications are allowed")
case "denied":
print("Notifications are denied")
case "notYetRequested":
print("Permission not yet requested")
default:
print("Unknown permission status")
}
Subscription
subscribe
Subscribe the user to receive push notifications. Use this method when you want to subscribe a user who has previously unsubscribed.
Syntax
subscribe(completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
completionHandler: A completion handler that is called when the subscription operation is complete.
response: A boolean indicating the subscription result.- Will be
trueif the user was successfully subscribed to push notifications. - Will be
falseif the subscription operation failed.
- Will be
error: An optional Error object that contains details if the subscription failed.- This will be
nilif the operation completed successfully.
- This will be
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif successfully subscribed.error(Error?): An error object if the operation failed,nilon success.
Usage
- Swift
- Objective-C
PushEngage.subscribe { response, error in
if response {
print("Successfully subscribed to notifications.")
return
}
if let error = error {
print("Failed to subscribe: \(error.localizedDescription)")
} else {
print("Unknown error occurred while subscribing.")
}
}
[PushEngage subscribeWithCompletionHandler:^(BOOL response, NSError * _Nullable error) {
if (response) {
NSLog(@"Successfully subscribed to notifications.");
return;
}
if (error) {
NSLog(@"Failed to subscribe: %@", error.localizedDescription);
} else {
NSLog(@"Unknown error occurred while subscribing.");
}
}];
unsubscribe
Unsubscribe the current subscriber from receiving push notifications. Once unsubscribed, the subscriber will no longer receive any push notifications.
Syntax
unsubscribe(completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
completionHandler: A closure that is called when the unsubscription operation is complete.
response: A boolean indicating the unsubscription result.- Will be
trueif the user was successfully unsubscribed from push notifications. - Will be
falseif the unsubscription operation failed.
- Will be
error: An optional Error object that contains details if the unsubscription failed.- This will be
nilif the operation completed successfully.
- This will be
Returns
Delivered asynchronously via completionHandler:
result(Bool):trueif successfully unsubscribed.error(Error?): An error object if the operation failed,nilon success.
Usage
- Swift
- Objective-C
PushEngage.unsubscribe { result, error in
if result {
print("Successfully unsubscribed from push notifications")
return
}
if let error = error {
print("Failed to unsubscribe: \(error.localizedDescription)")
} else {
print("Unknown error occurred while unsubscribing")
}
}
[PushEngage unsubscribeWithCompletionHandler:^(BOOL result, NSError * _Nullable error) {
if (result) {
NSLog(@"Successfully unsubscribed from push notifications");
return;
}
if (error) {
NSLog(@"Failed to unsubscribe: %@", error.localizedDescription);
} else {
NSLog(@"Unknown error occurred while unsubscribing");
}
}];
getSubscriptionStatus
Check whether the user is currently subscribed to push notifications.
Syntax
getSubscriptionStatus(completionHandler: @escaping (_ isSubscribed: Bool, _ error: Error?) -> Void)
Parameters
completionHandler: A closure that provides the subscription status when the check is complete.
isSubscribed: A boolean indicating the user's subscription status.- Will be
trueif the user is subscribed to push notifications. - Will be
falseif the user is unsubscribed from push notifications.
- Will be
error: An optional Error object that contains details if the status check failed.- This will be
nilif the operation completed successfully.
- This will be
Returns
Delivered asynchronously via completionHandler:
isSubscribed(Bool):trueif the user is subscribed,falseif unsubscribed.error(Error?): An error object if the status check failed,nilon success.
Usage
- Swift
- Objective-C
PushEngage.getSubscriptionStatus { isSubscribed, error in
if let error = error {
print("Failed to get subscription status: \(error.localizedDescription)")
return
}
print("Is subscribed: \(isSubscribed)")
}
[PushEngage getSubscriptionStatusWithCompletionHandler:^(BOOL isSubscribed, NSError * _Nullable error) {
if (error) {
NSLog(@"Failed to get subscription status: %@", error.localizedDescription);
return;
}
NSLog(@"Is subscribed: %d", isSubscribed);
}];
getSubscriptionNotificationStatus
Check whether user can receive push notification.
This method checks both the user's subscription status to push notification and their system-level notification permission status. A user can receive notifications only if they are subscribed to push notification and system-level notification permission status is granted.
Syntax
getSubscriptionNotificationStatus(completionHandler: @escaping (_ canReceiveNotifications: Bool, _ error: Error?) -> Void)
Parameters
completionHandler: A closure that is called when the status check is complete.
canReceiveNotifications: A boolean indicating whether the user can receive notifications.- Will be
trueif the user is both subscribed and has notification permissions granted. - Will be
falseif the user is unsubscribed or has notification permissions denied.
- Will be
error: An optional Error object that contains details if the status check failed.- This will be
nilif the operation completed successfully.
- This will be
Returns
Delivered asynchronously via completionHandler:
canReceiveNotifications(Bool):trueif the subscriber can receive notifications.error(Error?): An error object if the status check failed,nilon success.
Usage
PushEngage.getSubscriptionNotificationStatus { canReceiveNotifications, error in
if let error = error {
print("Failed to get notification status: \(error.localizedDescription)")
return
}
if canReceiveNotifications {
print("User can receive push notifications")
} else {
print("User cannot receive push notifications")
}
}
Associate Profile ID
Profile IDs serve as unique identifiers for your subscribers, enabling you to recognize them across multiple devices. Each subscriber can be assigned just one profile ID. This ID should be a string, and you have the flexibility to use any value, such as an email or phone number.
getSubscriberId
Retrieve the unique subscriber ID assigned to the current device by PushEngage.
Syntax
getSubscriberId(completion: @escaping (_ response: String?) -> Void)
Parameters
| Parameter | Type | Description |
|---|---|---|
completion | closure | Called with the subscriber ID string, or nil if not yet subscribed. |
Returns
Delivered asynchronously via completion:
response(String?): The unique subscriber identifier, ornilif the device is not yet subscribed.
Usage
PushEngage.getSubscriberId { subscriberId in
if let subscriberId = subscriberId {
print("Subscriber ID: \(subscriberId)")
} else {
print("Not yet subscribed")
}
}
addProfile
This method allows you to set a profile ID for the current subscriber. If a profile ID already exists, it will be replaced with the new value.
Syntax
addProfile(for id: String, completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
id: The subscriber ID to associate with the SDK.
completionHandler: A completion handler that provides the response of the method call as a boolean value, along with an optional error if the operation fails.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif the profile was associated successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
- Swift
- Objective-C
PushEngage.addProfile(for: "USER_ID") { response, error in
if response {
print("Profile associated successfully.")
} else if let error = error {
print("Failed to associate profile: \(error.localizedDescription)")
}
}
[PushEngage addProfileFor:@"USER_ID" completionHandler:^(BOOL response, NSError * _Nullable error) {
if (response) {
NSLog(@"Profile associated successfully.");
} else if (error) {
NSLog(@"Failed to associate profile: %@", error.localizedDescription);
}
}];
Subscriber Details
getSubscriberDetails
This method retrieves subscriber details based on a provided list of strings, which can include city, state, country, device, device type, segments, etc.
Syntax
getSubscriberDetails(for keys: [String]?, completionHandler: ((_ response: SubscriberDetailsData?, _ error: Error?) -> Void)?)
Parameters
keys (Optional): An optional array of strings specifying the specific keys of information to retrieve for the subscriber. If no keys are provided, the API will return complete subscriber details.
completionHandler: A closure that provides the response as a SubscriberDetailsData object representing the subscriber details, or an optional error object if any error occurs during the operation.
Returns
Delivered asynchronously via completionHandler:
response(SubscriberDetailsData?): The subscriber details object, ornilif not available.error(Error?): An error object if the retrieval failed,nilon success.
Usage
let keys = ["country", "city"] // Optional: Retrieve specific keys like country and city.
PushEngage.getSubscriberDetails(for: keys) { response, error in
if let subscriberDetails = response {
print("Subscriber Details: \(subscriberDetails)")
} else {
if let error = error {
print("Failed to retrieve subscriber details: \(error.localizedDescription)")
} else {
print("Unknown error occurred while retrieving subscriber details.")
}
}
}
Available Fields
| Field | Type | Description |
|---|---|---|
city | string | Subscriber's city |
state | string | Subscriber's state or region |
country | string | Subscriber's country |
device | string | Device name |
device_type | string | Device type (e.g., mobile, tablet) |
user_agent | string | App user agent string |
host | string | Host identifier |
timezone | string | Subscriber's timezone |
has_unsubscribed | boolean | Whether the subscriber has unsubscribed |
ts_created | string | ISO 8601 timestamp of subscription creation |
segments | array | Segment IDs the subscriber belongs to |
Segments
Segments are used to group subscribers so that you can send personalized notifications. Segments can be created based on attributes, categories, and more.
addSegments
This method enables you to add the current subscriber to segments.
Syntax
addSegments(_ segments: [String], completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
segments: An array of strings containing segment information to be added to the subscriber's profile.
completionHandler: A closure that provides a response indicating whether the operation was successful (true if successful, false otherwise) and an optional error object if any error occurs during the operation.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif segments were added successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
PushEngage.addSegments(["Segment1", "Segment2"]) { response, error in
if response {
print("Segments added successfully.")
} else {
if let error = error {
print("Failed to add segments: \(error.localizedDescription)")
} else {
print("Unknown error occurred while adding segments.")
}
}
}
addDynamicSegments
This method enables you to add the current subscriber to a segment for a specified duration, measured in days. After this period, the segment will be automatically removed from the subscriber.
Syntax
addDynamicSegments(_ dynamicSegments: [[String: Any]], completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
dynamicSegments: An array of dictionaries where the keys are strings and the values can be of any type. Each dictionary represents a dynamic segment with a "name" key (string) and a "duration" key (integer) indicating the duration of the segment in days.
completionHandler: A closure that provides a boolean response indicating whether the operation was successful (true if successful, false otherwise) and an optional error object if any error occurs during the operation.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif dynamic segments were added successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
let dynamicSegments: [[String: Any]] = [
["name": "Cricket", "duration": 3],
["name": "Tennis", "duration": 7],
]
PushEngage.addDynamicSegments(dynamicSegments) { response, error in
if response {
print("Dynamic segments updated successfully.")
} else {
if let error = error {
print("Failed to update dynamic segments: \(error.localizedDescription)")
} else {
print("Unknown error occurred while updating dynamic segments.")
}
}
}
removeSegments
This method allows you to remove the current subscriber from segments.
Syntax
removeSegments(_ segments: [String], completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
segments: An array of strings representing the segment names to be removed from the subscriber.
completionHandler: A completion handler that provides the response of the method call as a boolean value, along with an optional error if the operation fails.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif segments were removed successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
PushEngage.removeSegments(["SegmentToRemove"]) { response, error in
if response {
print("Segments removed successfully.")
} else {
if let error = error {
print("Failed to remove segments: \(error.localizedDescription)")
} else {
print("Unknown error occurred while removing segments.")
}
}
}
Attributes
Attributes are key-value pairs that allow you to store additional information about your subscribers. You can utilize attributes to segment your subscribers and send personalized notifications.
add
Use this method to add or update attributes for a subscriber. If an attribute with the specified key already exists, the existing value will be replaced.
Syntax
add(attributes: Parameters, completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
attributes: A dictionary representing the attributes to be added or updated. Should be in the format ["attributeName": attributeValue].
completionHandler: A closure that gets called after the update operation is completed. The closure provides a response boolean indicating success or failure and an optional error.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif attributes were added successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
let attributes = ["name": "Bob", "age": 30]
PushEngage.add(attributes: attributes) { success, error in
if success {
print("Attributes added/updated successfully.")
} else {
if let error = error {
print("Error occurred: \(error.localizedDescription)")
} else {
print("Unknown error occurred.")
}
}
}
The attributes parameter supports [String: Any] type, allowing for a variety of attribute types to be added.
set
This method allows you to set attributes for a subscriber, replacing any previously associated attributes. Use this method when you need to entirely reset the attributes with new values.
Syntax
set(attributes: Parameters, completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
attributes: A dictionary representing the attributes to be added. Should be in the format ["attributeName": attributeValue].
completionHandler: A closure that gets called after the update operation is completed. The closure provides a response boolean indicating success or failure and an optional error.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif attributes were set successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
let attributes = ["name": "Bob", "age": 30]
PushEngage.set(attributes: attributes) { success, error in
if success {
print("Attributes added successfully.")
} else {
if let error = error {
print("Error occurred: \(error.localizedDescription)")
} else {
print("Unknown error occurred.")
}
}
}
The attributes parameter supports [String: Any] type, allowing for a variety of attribute types to be added or updated.
getSubscriberAttributes
Retrieve the attributes associated with the current subscriber using this method.
Syntax
getSubscriberAttributes(completionHandler: @escaping(_ attributes: [String: Any]?, _ error: Error?) -> Void)
Parameters
completionHandler: A completion handler that is called when the attribute retrieval is complete.
attributes: A dictionary containing the subscriber attributes as [String: Any]?.- Will contain the subscriber's attributes if successfully retrieved.
- Will be
nilif no attributes are found or retrieval fails.
error: An optional Error object that contains details if the attribute retrieval failed.- This will be
nilif the operation completed successfully.
- This will be
Returns
Delivered asynchronously via completionHandler:
attributes([String: Any]?): A dictionary of attribute key-value pairs, ornilif none exist.error(Error?): An error object if the retrieval failed,nilon success.
Usage
PushEngage.getSubscriberAttributes { attributes, error in
if let attributes = attributes {
print("Subscriber attributes retrieved successfully: \(attributes)")
} else {
if let error = error {
print("Error occurred: \(error.localizedDescription)")
} else {
print("Unknown error occurred.")
}
}
}
deleteSubscriberAttributes
This method allows you to remove one or more attributes from the current subscriber. Provide an array of attribute names you wish to remove. Passing an empty array will result in the removal of all the subscriber's attributes.
Syntax
deleteSubscriberAttributes(for keys: [String], completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
keys: An array of strings representing the attribute keys to be removed. Pass an empty array to remove all subscriber attributes associated with the device.
completionHandler: A completion handler that provides the response of the API call as a boolean value, along with an optional error if the operation fails.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif attributes were deleted successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
PushEngage.deleteSubscriberAttributes(for: ["AttributeKeyToDelete"]) { response, error in
if response {
print("Attributes deleted successfully.")
} else {
if let error = error {
print("Failed to delete attributes: \(error.localizedDescription)")
} else {
print("Unknown error occurred while deleting attributes.")
}
}
}
Automated Notifications
Automated notifications include all types of triggered campaigns such as cart abandonment, price drop, back in stock, and browse abandonment. By default, automated notifications are enabled for all subscribers.
automatedNotification
Enable or disable all automated (triggered) notifications for the current subscriber.
Syntax
automatedNotification(status: TriggerStatusType, completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
status: A TriggerStatusType value indicating whether to enable or disable triggered campaigns.
.enabled— Enable automated notifications for this subscriber..disabled— Disable automated notifications for this subscriber.
completionHandler: A completion handler called when the operation completes.
response(Bool):trueif the status was updated successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
// Enable automated notifications
PushEngage.automatedNotification(status: .enabled) { response, error in
if response {
print("Automated notifications enabled")
} else if let error = error {
print("Failed to enable: \(error.localizedDescription)")
}
}
// Disable automated notifications
PushEngage.automatedNotification(status: .disabled) { response, error in
if response {
print("Automated notifications disabled")
} else if let error = error {
print("Failed to disable: \(error.localizedDescription)")
}
}
Triggered Campaigns
sendTriggerEvent
Detect your visitor's behavior to send automated push notifications to the right person at the right time.
Syntax
sendTriggerEvent(triggerCampaign: TriggerCampaign, completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
triggerCampaign: The TriggerCampaign object representing the campaign event to be triggered.
completionHandler: A completion handler that provides the response of the method call as a boolean value, along with an optional error if the operation fails.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif the trigger event was sent successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
let triggerCampaign = TriggerCampaign(campaignName: "name_of_campaign",
eventName: "name_of_event",
referenceId: "your_reference_id", //optional
profileId: nil, //optional
data: ["custom_key": "custom_value"] //optional
)
PushEngage.sendTriggerEvent(triggerCampaign: triggerCampaign) { result, error in
if result {
print("Send Trigger Alert Successful")
} else {
print("Failure")
}
}
addAlert
Re-engage your customers and increase conversion using Price Drop Alert Campaigns and Inventory Alert Campaigns.
Syntax
addAlert(triggerAlert: TriggerAlert, completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
triggerAlert: The TriggerAlert object representing the alert to be added.
completionHandler: A completion handler that provides the response of the method call as a boolean value, along with an optional error if the operation fails.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif the trigger alert was added successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
- Price Drop
- Back in Stock Alert
let triggerAlert = TriggerAlert(type: .priceDrop,
productId: "product_id",
link: "product_link",
price: 100.0,
variantId: "product_variant_id", //optional
expiryTimestamp: nil, //optional, Date?
alertPrice: 102.0, //optional, defaults to price if not set
availability: .inStock, //optional, default for priceDrop
data: ["custom_key": "custom_value"] //optional
)
PushEngage.addAlert(triggerAlert: triggerAlert) { result, error in
if result {
print("Add Alert Successful")
} else {
print("Failure")
}
}
let triggerAlert = TriggerAlert(type: .inventory,
productId: "product_id",
link: "product_link",
price: 100.0,
variantId: "product_variant_id", //optional
expiryTimestamp: nil, //optional, Date?
availability: .outOfStock, //optional, default for inventory
data: ["custom_key": "custom_value"] //optional
)
PushEngage.addAlert(triggerAlert: triggerAlert) { result, error in
if result {
print("Add Alert Successful")
} else {
print("Failure")
}
}
Goal Tracking
Goal Tracking will help you assign conversion goals & value to your notification campaigns. You can set up a default goal and have it integrated for all your campaigns.
sendGoal
Syntax
sendGoal(goal: Goal, completionHandler: ((_ response: Bool, _ error: Error?) -> Void)?)
Parameters
goal: Goal object representing the goal to be tracked.
completionHandler: A completion handler that provides the response of the method call as a boolean value, along with an optional error if the operation fails.
Returns
Delivered asynchronously via completionHandler:
response(Bool):trueif the goal was tracked successfully.error(Error?): An error object if the operation failed,nilon success.
Usage
- Swift
- Objective-C
let goal = Goal(name: "purchase", count: 1, value: 10.0)
PushEngage.sendGoal(goal: goal) { response, error in
if response {
print("Goal tracked successfully")
} else if let error = error {
print("Failed to track goal: \(error.localizedDescription)")
}
}
Goal *goal = [[Goal alloc] initWithName:@"purchase" count:@1 value:@10.0];
[PushEngage sendGoalWithGoal:goal completionHandler:^(BOOL response, NSError * _Nullable error) {
if (response) {
NSLog(@"Goal tracked successfully");
} else if (error) {
NSLog(@"Failed to track goal: %@", error.localizedDescription);
}
}];
Deep Linking
setNotificationOpenHandler
Use this method to set the notification open handler during SDK initialization. When a notification is opened, this handler will take the necessary action and provide the required user information for deep linking.
Syntax
setNotificationOpenHandler(block: PENotificationOpenHandler?)
Parameters
block: A closure of type PENotificationOpenHandler? that handles the notification open action.
- This closure is called when a notification is opened by the user.
- Use this closure to perform specific actions based on the opened notification.
Usage
PushEngage.setNotificationOpenHandler { result in
// Handle notification open action here
if let actionID = result.notificationAction.actionID {
switch actionID {
case "Your_Custom_Action_ID_1":
// Handle custom action 1
case "Your_Custom_Action_ID_2":
// Handle custom action 2
default:
// Handle default action
}
}
}
Notification Handlers
setNotificationWillShowInForegroundHandler
Use this method to set the notification handler for when notifications are received while the app is in foreground mode. This allows you to handle notifications effectively when the app is active and in the foreground.
Syntax
setNotificationWillShowInForegroundHandler(block: PENotificationWillShowInForeground?)
Parameters
block: A closure of type PENotificationWillShowInForeground? that handles notifications received while the app is in the foreground.
- This closure is passed from the AppDelegate.
- Allows you to customize the behavior when dealing with incoming notifications in the foreground.
Usage
PushEngage.setNotificationWillShowInForegroundHandler { notification, completion in
//Replace with your custom code
if notification.contentAvailable == 1 {
// In case a completion handler is not set, it will be called after 25 seconds.
completion?(nil)
} else {
completion?(notification)
}
}
receivedRemoteNotification
Handle Remote Notifications Manually.
Use this method to handle remote notifications manually if swizzling is not used or if you want to customize the notification handling behavior.
Syntax
receivedRemoteNotification(application:userInfo:completionHandler:)
Parameters
application: UIApplication instance.
userInfo: The remote notification payload received from APNs as [AnyHashable: Any].
completionHandler: The completion handler provided by the host application for background fetch completion. This handler must be called after processing the notification.
Returns
A boolean value indicating if any background work was started by the SDK.
Usage
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let didStartBackgroundWork = PushEngage.receivedRemoteNotification(application: application,
userInfo: userInfo,
completionHandler: completionHandler)
if !didStartBackgroundWork {
// Handle the notification in the foreground, if required.
}
}
willPresentNotification
Handle the presentation of notifications while the app is in the foreground.
Use this method to manage how a notification is presented when the app is active. By default, notifications may not be shown when the app is active, but this method allows you to control whether they should be presented.
Syntax
willPresentNotification(center:notification:completionHandler:)
Parameters
center: The UNUserNotificationCenter responsible for delivering the notification.
notification: The UNNotification object containing the notification information that was delivered.
completionHandler: A completion handler to execute with the desired notification presentation options.
Usage
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
PushEngage.willPresentNotification(center: center, notification: notification, completionHandler: completionHandler)
}
didReceiveRemoteNotification
Handles the remote notification interaction for devices running iOS 10.0 and above.
This method should be implemented in the application's UNUserNotificationCenterDelegate to process the response of a remote notification if swizzling is not used. When a user interacts with a notification, this method should be called to handle the response and perform appropriate actions based on the user's interaction.
Syntax
didReceiveRemoteNotification(with notification: UNNotificationResponse)
Parameters
notification: The UNNotificationResponse object representing the user's response to a remote notification.
- Contains information about the notification that was interacted with.
- Includes details about the user's action (tap, dismiss, etc.).
Usage
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
PushEngage.didReceiveRemoteNotification(with: response)
// Handle the response and perform appropriate actions based on user's interaction
// Call the completion handler after processing the notification
completionHandler()
}
Notification Extensions
getCustomUIPayLoad
Get Custom UI Payload for Notification. Use this method to get the custom UI payload associated with a notification request.
Syntax
getCustomUIPayLoad(for request: UNNotificationRequest) -> CustomUIModel
Parameters
request: The UNNotificationRequest object for which you want to retrieve the custom UI payload.
- This should be the notification request received from the system.
- Contains the notification content and metadata needed to extract the custom UI payload.
Returns
A CustomUIModel object containing the custom UI payload for the given notification request.
Usage
class NotificationViewController: UIViewController, UNNotificationContentExtension {
func didReceive(_ notification: UNNotification) {
if #available(iOS 10.0, *) {
let customUIPayload = PushEngage.getCustomUIPayLoad(for: notification.request)
// Process custom UI payload here
}
}
}
didReceiveNotificationExtensionRequest
Modify the notification content received from the parent application in the Notification Service Extension.
Syntax
didReceiveNotificationExtensionRequest(_ request: UNNotificationRequest, bestContentHandler: UNMutableNotificationContent)
Parameters
request: The UNNotificationRequest received from the parent application.
bestContentHandler: The UNMutableNotificationContent that can be modified to customize the notification.
Usage
class NotificationService: UNNotificationServiceExtension {
var contentHandler: ((UNNotificationContent) -> Void)?
var bestAttemptContent: UNMutableNotificationContent?
var request : UNNotificationRequest?
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.request = request
self.contentHandler = contentHandler
self.bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
if let bestContent = bestAttemptContent {
PushEngage.didReceiveNotificationExtensionRequest(request, bestContentHandler: bestContent)
contentHandler(bestContent)
}
}
}
serviceExtensionTimeWillExpire
Use this method in the notification service extension to handle notification content just before the extension gets terminated.
Syntax
serviceExtensionTimeWillExpire(_ request: UNNotificationRequest, content: UNMutableNotificationContent?) -> UNMutableNotificationContent?
Parameters
request: The original UNNotificationRequest received by the extension.
content: The mutable content for the notification. This content can be modified as needed before delivery.
Returns
The modified UNMutableNotificationContent that will be delivered to the user.
Usage
class NotificationService: UNNotificationServiceExtension {
override func serviceExtensionTimeWillExpire() {
if let contentHandler = contentHandler, let request = request ,let bestAttemptContent = bestAttemptContent {
guard let content = PushEngage.serviceExtensionTimeWillExpire(request, content: bestAttemptContent) else {
contentHandler(bestAttemptContent)
return
}
contentHandler(content)
}
}
}
Utilities
setBadgeCount
Set the badge count for the application icon. This method allows you to update the numeric badge displayed on the application's icon.
Syntax
setBadgeCount(count: Int)
Parameters
count: An integer value representing the number to be displayed as the badge.
- Use any positive integer to display that number as the badge.
- Use
0to remove the badge completely.
Usage
PushEngage.setBadgeCount(count: 5)
enableLogging
Enables or disables verbose debug logging for the SDK. When enabled, the SDK prints detailed diagnostic output to the Xcode console.
Set enableLogging to false before releasing to the App Store to avoid leaking internal SDK state to device logs.
Syntax
enableLogging: Bool
Usage
// Enable during development
PushEngage.enableLogging = true
// Disable for production
PushEngage.enableLogging = false
getSdkVersion
Retrieve the current version string of the PushEngage iOS SDK.
Syntax
getSdkVersion() -> String
Parameters
None
Returns
A String containing the current SDK version (e.g., "1.0.0").
Usage
let version = PushEngage.getSdkVersion()
print("PushEngage SDK version: \(version)")