Display Interactive Notifications

Use interactive notifications to add buttons to push notifications from your mobile app.

This code example shows how to configure the SDK to display interactive notifications.

1func configureSdk() -> Bool {
2
3  // Enable logging for debugging early on. Debug level is not recommended for
4  // production apps because a large amount of data is logged to the console.
5
6  #if DEBUG
7    SFMCSdk.setLogger(logLevel: .debug)
8  #endif
9
10  // Use the `PushFeatureConfigBuilder` to configure the Push Feature SDK. This
11  // gives you the maximum flexibility in SDK configuration. The builder lets you
12  //configure the module parameters at runtime.
13
14  let pushFeatureConfiguration = PushFeatureConfigBuilder()
15    .setApplicationControlsBadging(true)
16    .build()
17
18  // Set the completion handler to take action when all modules initialization
19  // is completed. Setting the completion handler is optional.
20
21  let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in
22    DispatchQueue.main.async {
23      self?.handleSDKInitializationCompletion(status: status)
24    }
25  }
26
27  SFMCSdk.initializeSdk(
28    ConfigBuilder().setPushFeature(config: pushFeatureConfiguration).build(),
29    completion: completionHandler)
30
31  return true
32}
33
34// MARK: - SDK Initialization Completion Handler
35
36private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) {
37  var allSuccessful = true
38
39  for moduleStatus in status {
40    print(
41      "Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)")
42
43    if moduleStatus.initStatus == .success {
44      // Handle successful initialization for each module
45      switch moduleStatus.moduleName {
46      case .pushFeature:
47        setupPushFeature()
48      default:
49        break
50      }
51    } else if moduleStatus.initStatus == .error {
52      allSuccessful = false
53      // module failed to initialize, check logs for more details
54    } else if moduleStatus.initStatus == .cancelled {
55      allSuccessful = false
56      // module initialization was cancelled
57      // (for example if re-configuration was triggered before init completed)
58    } else if moduleStatus.initStatus == .timeout {
59      allSuccessful = false
60      // module failed to initialize due to timeout, check logs for more details
61    }
62  }
63  if allSuccessful {
64    print("SDK initialization completed successfully")
65  } else {
66    print("SDK initialization completed with errors - check logs above")
67  }
68}
69
70func setupPushFeature() {
71  // Set the URLHandlingDelegate to handle URLs from CloudPage, OpenDirect,
72  // Location, and Inbox messages. In this example, the AppDelegate class adheres
73  // to the URLHandlingDelegate protocol (see below).
74  PushFeature.requestSdk { pushFeature in
75    DispatchQueue.main.async {
76      pushFeature?.setURLHandlingDelegate(self)
77    }
78  }
79
80  // Make sure to dispatch this to the main thread, as UNUserNotificationCenter
81  // will present UI.
82  DispatchQueue.main.async {
83    // Set the UNUserNotificationCenterDelegate to a class adhering to this protocol.
84    // In this example, the AppDelegate class adheres to the protocol (see below)
85    // and handles Notification Center delegate methods from iOS.
86    UNUserNotificationCenter.current().delegate = self
87
88    // Request authorization from the user for push notification alerts.
89    UNUserNotificationCenter.current().requestAuthorization(
90      options: [.alert, .sound, .badge],
91      completionHandler: { (_ granted: Bool, _ error: Error?) -> Void in
92        if error == nil {
93          if granted == true {
94            DispatchQueue.main.async {
95              UIApplication.shared.registerForRemoteNotifications()
96            }
97            // Support notification categories
98            let exampleAction = UNNotificationAction(
99              identifier: "App", title: "Example", options: [])
100            let appCategory = UNNotificationCategory(
101              identifier: "Example", actions: [exampleAction],
102              intentIdentifiers: [] as? [String] ?? [String](), options: [])
103            let categories = Set<AnyHashable>([appCategory])
104            UNUserNotificationCenter.current().setNotificationCategories(
105              categories as? Set<UNNotificationCategory> ?? Set<UNNotificationCategory>())
106          }
107        }
108      }
109    )
110  }
111}
112
113func application(
114  _ application: UIApplication,
115  didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
116) -> Bool {
117  self.configureSFMCSdk()
118  return true
119}

Handle Actions 

In your push handler, examine the push notification’s payload to see if your action is triggered and if your application performed the action, as shown in this code example.

1// The method is called on the delegate when the user responds to the notification
2// by opening the application, dismissing the notification, or choosing a
3// UNNotificationAction. The delegate must be set before the application returns
4//from applicationDidFinishLaunching:.
5func userNotificationCenter(
6  _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse,
7  withCompletionHandler completionHandler: @escaping () -> Void
8) {
9  // tell the SDK about the notification
10  PushFeature.requestSdk { pushFeature in
11    pushFeature?.setNotificationResponse(response)
12  }
13  // Check your notification custom actions
14  if response.actionIdentifier == "App" {
15    // Handle your notification’s custom action here
16  }
17}