Enable Push Notifications on iOS

After you integrate and configure the SDK, enable push notifications in your iOS app. This process involves enabling push capabilities in Xcode, implementing the required delegate protocols, and registering for remote notifications.

  1. In Xcode, on the Signing & Capabilities tab for your app, enable push notifications.

  2. Set your AppDelegate class to adhere to the UIApplicationDelegate and UNUserNotificationCenterDelegate protocol.

    1class AppDelegate: UIApplicationDelegate, UNUserNotificationCenterDelegate
    2...
  3. Extend the SDK configuration code to add support for push registration.

    Code example for version 10 and later

    If your app uses version 10 or later of the SDK, use this code.

    1// REQUIRED IMPLEMENTATION
    2  func configureSdk() -> Bool {
    3
    4    // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data
    5    // about the SDK will be logged to the console.
    6    #if DEBUG
    7      SFMCSdk.setLogger(logLevel: .debug)
    8    #endif
    9
    10    // Use the `PushFeatureConfigBuilder` to configure the Push Feature SDK. This gives you the maximum flexibility in SDK configuration.
    11    // The builder lets you configure the module parameters at runtime.
    12
    13    let pushFeatureConfiguration = PushFeatureConfigBuilder()
    14      .setApplicationControlsBadging(true)
    15      .build()
    16
    17    // Set the completion handler to take action when all modules initialization is completed.
    18    // Setting the completion handler is optional.
    19
    20    let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in
    21      DispatchQueue.main.async {
    22        self?.handleSDKInitializationCompletion(status: status)
    23      }
    24    }
    25
    26    SFMCSdk.initializeSdk(ConfigBuilder().setMAM(
    27      config: pushFeatureConfiguration).build(),
    28      completion: completionHandler
    29    )
    30
    31    return true
    32  }
    33
    34  // MARK: - SDK Initialization Completion Handler
    35
    36  private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) {
    37    var allSuccessful = true
    38
    39    for moduleStatus in status {
    40      print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)")
    41
    42      if moduleStatus.initStatus == .success {
    43        // Handle successful initialization for each module
    44        switch moduleStatus.moduleName {
    45        case .pushFeature:
    46          setupPushFeature()
    47        default:
    48          break
    49        }
    50      } else if moduleStatus.initStatus == .error {
    51        allSuccessful = false
    52        // module failed to initialize, check logs for more details
    53      } else if moduleStatus.initStatus == .cancelled {
    54        allSuccessful = false
    55        // module initialization was cancelled (for example if the
    56        // re-configuration was triggered before initialization completed)
    57      } else if moduleStatus.initStatus == .timeout {
    58        allSuccessful = false
    59        // module failed to initialize due to timeout, check logs for more details
    60      }
    61    }
    62    if allSuccessful {
    63      print("SDK initialization completed successfully")
    64    } else {
    65      print("SDK initialization completed with errors - check logs above")
    66    }
    67  }
    68
    69  func setupPushFeature() {
    70    // Set the URLHandlingDelegate to handle URLs from CloudPage, OpenDirect,
    71    //Location, and Inbox messages. In this example, the AppDelegate class adheres
    72    // to the URLHandlingDelegate protocol (see below).
    73    PushFeature.requestSdk { pushFeature in
    74      DispatchQueue.main.async {
    75        pushFeature?.setURLHandlingDelegate(self)
    76      }
    77    }
    78  }
    79
    80  func application(
    81    _ application: UIApplication,
    82    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
    83  ) -> Bool {
    84    self.configureSdk()
    85    return true
    86  }
    Code example for version 8 and 9 If your app uses version 8 or 9 of the SDK, use this code.
    1// SDK: REQUIRED IMPLEMENTATION
    2  func configureSDK() {
    3    #if DEBUG
    4      SFMCSdk.setLogger(logLevel: .debug)
    5    #endif
    6
    7    let mobilePushConfiguration = PushConfigBuilder(appId: appId)
    8      .setAccessToken(accessToken)
    9      .setMarketingCloudServerUrl(appEndpoint)
    10      .setMid(mid)
    11      .setInboxEnabled(inbox)
    12      .setLocationEnabled(location)
    13      .setAnalyticsEnabled(analytics)
    14      .build()
    15
    16    let completionHandler: (OperationResult) -> () = { result in
    17      if result == .success {
    18        self.setupMobilePush()
    19      }
    20    }
    21
    22    SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build())
    23  }
    24
    25  func setupMobilePush() {
    26
    27    // Set the MarketingCloudSDKURLHandlingDelegate to a class adhering to the protocol.
    28    // In this example, the AppDelegate class adheres to the protocol (see below)
    29    // and handles URLs passed back from the SDK.
    30    SFMCSdk.requestPushSdk { mp in
    31      mp.setURLHandlingDelegate(self)
    32    }
    33
    34    // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will present UI.
    35    DispatchQueue.main.async {
    36      // Set the UNUserNotificationCenterDelegate to a class adhering to the protocol.
    37      // In this example, the AppDelegate class adheres to the protocol (see below)
    38      // and handles Notification Center delegate methods from iOS.
    39      UNUserNotificationCenter.current().delegate = self
    40
    41        // Request authorization from the user for push notification alerts.
    42        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in
    43          if error == nil {
    44            if granted == true {
    45              // Your application may want to do something specific if the user has granted authorization
    46              // for the notification types specified; it would be done here.
    47            }
    48          }
    49        })
    50
    51        // In any case, your application should register for remote notifications *each time*
    52        // your application launches to ensure that the push token used by MobilePush (for silent push)
    53        // is updated if necessary.
    54
    55        // Registering in this manner does *not* mean that a user will see a notification - it only means
    56        // that the application will receive a unique push token from iOS.
    57        UIApplication.shared.registerForRemoteNotifications()
    58    }
    59  }
    Code example for version 7 This code example shows how to configure the version 7 of the SDK for iOS apps.
    1func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    2
    3    // ... SDK configuration setup
    4
    5    var success = false
    6
    7    do {
    8        try MarketingCloudSDK.sharedInstance().sfmc_configure(with:builder)
    9        success = true
    10    } catch let error as NSError {
    11        // Errors returned from configuration will be in the NSError parameter and can be used to determine
    12        // if you've implemented the SDK correctly.
    13
    14        let configErrorString = String(format: "MarketingCloudSDK sfmc_configure failed with error = %@", error)
    15        print(configErrorString)
    16    }
    17
    18    if success == true {
    19        // The SDK has been fully configured and is ready for use!
    20
    21        // Enable logging for debugging. Not recommended for production apps, as significant data
    22        // about MobilePush will be logged to the console.
    23        #if DEBUG
    24        MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true)
    25        #endif
    26
    27        // Set the MarketingCloudSDKURLHandlingDelegate to a class adhering to the protocol.
    28        // In this example, the AppDelegate class adheres to the protocol
    29        // and handles URLs passed back from the SDK.
    30        MarketingCloudSDK.sharedInstance().sfmc_setURLHandlingDelegate(self)
    31
    32        // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will present UI.
    33        DispatchQueue.main.async {
    34            if #available(iOS 10.0, *) {
    35                // Set the UNUserNotificationCenterDelegate to a class adhering to thie protocol.
    36                // In this exmple, the AppDelegate class adheres to the protocol (see below)
    37                // and handles Notification Center delegate methods from iOS.
    38                UNUserNotificationCenter.current().delegate = self
    39
    40                // Request authorization from the user for push notification alerts.
    41                UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) -> Void in
    42                    if error == nil {
    43                        if granted == true {
    44                            // Your application may want to do something specific
    45                            // if the user has granted authorization for the
    46                            // notification types specified; it would be done here.
    47                            print(MarketingCloudSDK.sharedInstance().sfmc_deviceToken() ?? "error: no token - was UIApplication.shared.registerForRemoteNotifications() called?")
    48                        }
    49                    }
    50                })
    51            }
    52
    53            // In any case, your application should register for remote notifications *each time*
    54            // your application launches to ensure that the push token used by MobilePush (for silent push) is updated if necessary.
    55
    56            // Registering in this manner does *not* mean that a user will see a notification,
    57            // it only means that the application will receive a unique push token from iOS.
    58            UIApplication.shared.registerForRemoteNotifications()
    59        }
    60    }
    61
    62    return true
    63}
  4. Add the required UIApplicationDelegate protocol methods to support push registration to your AppDelegate class.

    Code example for version 10 and later

    If your app uses version 10 or later of the SDK, use this code.

    1// PushFeature SDK: REQUIRED IMPLEMENTATION
    2func application(_ application: UIApplication,
    3  didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    4  PushFeature.requestSdk { pushFeature in
    5    pushFeature?.setDeviceToken(deviceToken)
    6  }
    7}
    8
    9// PushFeature SDK: REQUIRED IMPLEMENTATION
    10func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    11  print(error)
    12}
    13
    14// PushFeature SDK: REQUIRED IMPLEMENTATION
    15/**
    16This delegate method lets apps with the "remote-notification" background mode
    17fetch data in response to an incoming remote notification.
    18
    19Call the fetchCompletionHandler as soon as you're finished performing that
    20operation so the system can accurately estimate its power and data cost.
    21
    22This method is invoked even if the application was launched or resumed because
    23of the remote notification. The delegate methods are invoked first.
    24
    25This behavior is in contrast to `application(_:didReceiveRemoteNotification:)`,
    26which isn't called in those cases, and isn't invoked if this method is implemented.
    27**/
    28func application(
    29  _ application: UIApplication,
    30  didReceiveRemoteNotification userInfo: [AnyHashable : Any],
    31  fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    32    PushFeature.requestSdk { pushFeature in
    33      pushFeature?.setNotificationUserInfo(userInfo)
    34    }
    35  completionHandler(.newData)
    36}
    Code example for version 8 and 9

    If your app uses version 8 or 9 of the SDK, use this code.

    1// REQUIRED IMPLEMENTATION
    2    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    3        SFMCSdk.requestPushSdk { mp in
    4            mp.setDeviceToken(deviceToken)
    5        }
    6    }
    7
    8    // REQUIRED IMPLEMENTATION
    9    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    10        print(error)
    11    }
    12
    13    // REQUIRED IMPLEMENTATION
    14    /** This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification.
    15    //You should call the fetchCompletionHandler as soon as you’re finished performing that operation,
    16    // so the system can accurately estimate its power and data cost.
    17    // This method will be invoked even if the application was launched or resumed because of the remote notification.
    18    // The respective delegate methods will be invoked first.
    19    // Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented. **/
    20    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    21        SFMCSdk.requestPushSdk { mp in
    22            mp.setNotificationUserInfo(userInfo)
    23        }
    24        completionHandler(.newData)
    25    }
    Code example for version 7

    If your app uses version 7 of the SDK, use this code.

    1// REQUIRED IMPLEMENTATION
    2    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    3        MarketingCloudSDK.sharedInstance().sfmc_setDeviceToken(deviceToken)
    4    }
    5
    6    // REQUIRED IMPLEMENTATION
    7    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
    8        print(error)
    9    }
    10
    11    // REQUIRED IMPLEMENTATION
    12    /** This delegate method offers an opportunity for applications with the "remote-notification" background mode to fetch appropriate new data in response to an incoming remote notification.
    13    //You should call the fetchCompletionHandler as soon as you’re finished performing that operation, so the system can accurately estimate its power and data cost.
    14    // This method will be invoked even if the application was launched or resumed because of the remote notification.
    15    // The respective delegate methods will be invoked first. Note that this behavior is in contrast to application:didReceiveRemoteNotification:, which is not called in those cases, and which will not be invoked if this method is implemented. **/
    16    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    17        MarketingCloudSDK.sharedInstance().sfmc_setNotificationUserInfo(userInfo)
    18        completionHandler(.newData)
    19    }
  5. Add the required UNUserNotificationCenterDelegate protocol methods to support push notifications to your AppDelegate class.

    Code example for version 10 and later

    If your app uses version 10 or later of the SDK, use this code.

    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:.
    5 /// *
    6 func userNotificationCenter(
    7 _ center: UNUserNotificationCenter,
    8 didReceive response: UNNotificationResponse,
    9 withCompletionHandler completionHandler: @escaping () -> Void
    10 ) {
    11 // Required: Tell the SDK about the notification so that it begins to
    12 // collect analytics and process the notification for your app.
    13 PushFeature.requestSdk { pushFeature in
    14     pushFeature?.setNotificationResponse(response)
    15 }
    16 completionHandler()
    17 }
    18
    19 /// The method is called on the delegate only if the application is in the
    20 /// foreground. If the method isn't implemented or the handler isn't called in a
    21 /// timely manner, then the notification isn't shown. The application can
    22 /// have the notification presented as a sound, badge, alert, or it can appear
    23 /// in the notification list. This decision should be based on whether the
    24 /// information in the notification is otherwise visible to the user.
    25 /// *
    26 func userNotificationCenter(
    27 _ center: UNUserNotificationCenter,
    28 willPresent notification: UNNotification,
    29 withCompletionHandler completionHandler: @escaping (
    30     UNNotificationPresentationOptions
    31 ) -> Void
    32 ) {
    33 completionHandler(.alert)
    34 }
    Code example for version 9

    If your app uses version 9 of the SDK, use this code.

    1// REQUIRED IMPLEMENTATION
    2// The method will be called on the delegate when the user responded to the notification by opening the application,
    3// dismissing the notification or choosing a UNNotificationAction.
    4// The delegate must be set before the application returns from applicationDidFinishLaunching:.
    5@available(iOS 10.0, *)
    6func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    7    // Required: tell the MarketingCloudSDK about the notification. This will collect MobilePush analytics
    8    // and process the notification on behalf of your application.
    9    SFMCSdk.requestPushSdk { mp in
    10        mp.setNotificationResponse(response)
    11    }
    12    completionHandler()
    13}
    14
    15// REQUIRED IMPLEMENTATION
    16// The method will be called on the delegate only if the application is in the foreground.
    17// If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented.
    18// The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list.
    19// This decision should be based on whether the information in the notification is otherwise visible to the user.
    20@available(iOS 10.0, *)
    21func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    22    completionHandler(.alert)
    23}
    Code example for version 8

    If your app uses version 8 of the SDK, use this code.

    1// REQUIRED IMPLEMENTATION
    2// The method will be called on the delegate when the user responded to the notification by opening the application,
    3// dismissing the notification or choosing a UNNotificationAction.
    4// The delegate must be set before the application returns from applicationDidFinishLaunching:.
    5@available(iOS 10.0, *)
    6func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    7    // Required: tell the MarketingCloudSDK about the notification. This will collect MobilePush analytics
    8    // and process the notification on behalf of your application.
    9    SFMCSdk.requestPushSdk { mp in
    10        mp.setNotificationRequest(response.notification.request)
    11    }
    12    completionHandler()
    13}
    14
    15// REQUIRED IMPLEMENTATION
    16// The method will be called on the delegate only if the application is in the foreground.
    17// If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented.
    18// The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list.
    19// This decision should be based on whether the information in the notification is otherwise visible to the user.
    20@available(iOS 10.0, *)
    21func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    22    completionHandler(.alert)
    23}
    Code example for version 7

    If your app uses version 7 of the SDK, use this code.

    1// REQUIRED IMPLEMENTATION
    2// The method will be called on the delegate when the user responded to the notification by opening the application,
    3// dismissing the notification or choosing a UNNotificationAction.
    4// The delegate must be set before the application returns from applicationDidFinishLaunching:.
    5@available(iOS 10.0, *)
    6func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    7    // Required: Tell MarketingCloudSDK about the notification.
    8    // This will collect MobilePush analytics and process the notification on behalf of your application.
    9    MarketingCloudSDK.sharedInstance().sfmc_setNotificationRequest(response.notification.request)
    10    completionHandler()
    11}
    12
    13// REQUIRED IMPLEMENTATION
    14// The method will be called on the delegate only if the application is in the foreground.
    15// If the method is not implemented or the handler is not called in a timely manner then the notification will not be presented.
    16// The application can choose to have the notification presented as a sound, badge, alert and/or in the notification list.
    17// This decision should be based on whether the information in the notification is otherwise visible to the user.
    18@available(iOS 10.0, *)
    19func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    20    completionHandler(.alert)
    21}

The delegate methods in this procedure use Marketing Cloud SDK APIs to manage push notifications, contact registration, and analytics tracking. If you implement the delegate methods without calling the corresponding SDK methods, these features don’t work.

Note