Copy the relevant .xcframework directories from your downloads folder into your project folder.
In Xcode, open your project and select the appropriate target. Add the required .xcframework files to Frameworks, Libraries, and Embedded Content in the target’s General settings.
In Build Settings, add -ObjC to Other Linker Flags.
Configure the SDK
For reference documentation on SDK configuration methods, refer to these links:
The configuration example in this section uses the MarketingCloudSDK ConfigBuilder configuration method, as it’s the most flexible means to support your application’s usage of the MobilePush SDK.
Configuring the SDK using a JSON file is deprecated. Move existing implementations to the builder method. For more information about configuration methods, see the MarketingCloudSDKConfigBuilder reference for SDK version 7 and later, and the PushConfigBuilder reference for SDK versions 8 and later.
Important
All method names contain the prefix sfmc_. This convention allows the application implementing the SDK to avoid namespace collisions between the external libraries it uses. The MarketingCloudSDK doesn’t cause compile, link, or runtime collisions with other code your application implements. For more information, see Apple Developer Documentation: Customizing Existing Classes.
1import MarketingCloudSDK2import SFMCSDK3import UIKit45@main6class AppDelegate: UIResponder, UIApplicationDelegate {78 var window: UIWindow?910 // Marketing Cloud SDK Configuration11 let mcAppID = "<your MC appID here>"12 let mcAccessToken = "<your MC accessToken here>"13 let mcServerURL = "<your mc serverURL here>"14 let mcMid = "<your account MID here>"1516 // Define features of Marketing Cloud your app will use.17 let mcInboxEnabled = false18 let mcLocationEnabled = false19 let mcAnalyticsEnabled = true2021 // MarketingCloud SDK: REQUIRED IMPLEMENTATION22 @discardableResult2324 func configureSdk() ->Bool{2526 // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data27 // about the SDK will be logged to the console.2829 #if DEBUG30 SFMCSdk.setLogger(logLevel: .debug)31 #endif3233 // Use the `MarketingCloudSdkConfigBuilder` to configure the MarketingCloud SDK. This gives you the maximum flexibility in SDK configuration.34 // The builder lets you configure the module parameters at runtime.3536 let engagementConfiguration = MarketingCloudSdkConfigBuilder(appId: mcAppID)37 .setAccessToken(mcAccessToken)38 .setMarketingCloudServerUrl(URL(string: mcServerURL)!)39 .setMid(mcMid)40 .setInboxEnabled(mcInboxEnabled)41 .setLocationEnabled(mcLocationEnabled)42 .setAnalyticsEnabled(mcAnalyticsEnabled)43 .build()4445 // Set the completion handler to take action when all modules initialization is completed.46 // Seting the completion handler is optional.4748 let completionHandler: ((_ status: [ModuleInitStatus]) ->Void) = {[weak self] status in49 DispatchQueue.main.async{50 self?.handleSDKInitializationCompletion(status: status)51}52}5354 SFMCSdk.initializeSdk(55 ConfigBuilder().setEngagement(config: engagementConfiguration).build(),56 completion: completionHandler)5758 return true59}6061 // MARK: - SDK Initialization Completion Handler6263 private func handleSDKInitializationCompletion(status: [ModuleInitStatus]){64 var allSuccessful = true6566 for moduleStatus in status {67 print(68 "Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)")6970 if moduleStatus.initStatus == .success {71 // Handle successful initialization for each module72 switch moduleStatus.moduleName {73 case .engagement:74 // Handle successful initialization for Marketing cloud module75 default:76 break77}78}else if moduleStatus.initStatus == .error{79 allSuccessful = false80 // module failed to initialize, check logs for more details81}else if moduleStatus.initStatus == .cancelled {82 allSuccessful = false83 // module initialization was cancelled (for example due to re-confirguration triggered before init was completed)84}else if moduleStatus.initStatus == .timeout {85 allSuccessful = false86 // module failed to initialize due to timeout, check logs for more details87}88}89 if allSuccessful {90 print("SDK initialization completed successfully")91}else{92 print("SDK initialization completed with errors - check logs above")93}94}9596 func application(97 _ application: UIApplication,98 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?99) ->Bool{100 // Override point for customization after application launch.101 self.configureSdk()102 return true103}104105 // Marketing Cloud SDK: OPTIONAL IMPLEMENTATION (if using Data Protection)106 func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication){107 self.configureSdk()108}109}
If your app uses version 8 or 9 of the SDK, use this code.
SDK for iOS, version 8 or 9
1import SFMCSDK2import MarketingCloudSDK34class AppDelegate: UIResponder, UIApplicationDelegate {56 var window: UIWindow?78 // SDK: REQUIRED IMPLEMENTATION910 // The appID, accessToken and appEndpoint are required values for MobilePush SDK Module configuration and are obtained from your MobilePush app.11 // See https://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/get-started/get-started-setupapps.html for more information.12 #if DEBUG13 let appId = "[DEV-APNS App ID value from MobilePush app admin]"14 let accessToken = "[DEV-APNS Access Token value from MobilePush app admin]"15 let appEndpoint = "[DEV-APNS App Endpoint value from MobilePush app admin]"16 let mid = "[DEV-APNS account MID value from MobilePush app admin]"17 #else18 let appId = "[PROD-APNS appId value from MobilePush app admin]"19 let accessToken = "[PROD-APNS accessToken value from MobilePush app admin]"20 let appEndpoint = "[PROD-APNS app endpoint value from MobilePush app admin]"21 let mid = "[PROD-APNS account MID value from MobilePush app admin]"22 #endif232425 // Define features of MobilePush your app will use.26 let inbox = false27 let location = false28 let analytics = true2930 // SDK: REQUIRED IMPLEMENTATION31 func configureSDK(){32 // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data33 // about the MobilePush will be logged to the console.34 #if DEBUG35 SFMCSdk.setLogger(logLevel: .debug)36 #endif3738 // Use the Mobile Push Config Builder to configure the Mobile Push Module. This gives you the maximum flexibility in SDK configuration.39 // The builder lets you configure the module parameters at runtime.40 let mobilePushConfiguration = PushConfigBuilder(appId: appId)41 .setAccessToken(accessToken)42 .setMarketingCloudServerUrl(appEndpoint)43 .setMid(mid)44 .setInboxEnabled(inbox)45 .setLocationEnabled(location)46 .setAnalyticsEnabled(analytics)47 .build()4849 // Set the completion handler to take action when module initialization is completed. The result indicates if initialization was sucesfull or not.50 // Seting the completion handler is optional.51 let completionHandler: (OperationResult) ->() = { result in52 if result == .success {53 // module is fully configured and ready for use54}else if result == .error{55 // module failed to initialize, check logs for more details56}else if result == .cancelled {57 // module initialization was cancelled (for example due to re-confirguration triggered before init was completed)58}else if result == .timeout {59 // module failed to initialize due to timeout, check logs for more details60}61}6263 // Once you've created the mobile push configuration, intialize the SDK.64 SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build())65}6667 // SDK: REQUIRED IMPLEMENTATION68 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) ->Bool{69 self.configureSDK()7071 return true72}7374 // SDK: OPTIONAL IMPLEMENTATION (if using Data Protection)75 func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication){76 if(SFMCSdk.mp.getStatus() != .operational){77 self.configureSFMCSdk()78}79}80}
If your app uses version 7 of the SDK, use this code.
SDK for iOS, version 7
1import MarketingCloudSDK23class AppDelegate: UIResponder, UIApplicationDelegate {45 var window: UIWindow?67 // MobilePush SDK: REQUIRED IMPLEMENTATION89 // The appID, accessToken and appEndpoint are required values for MobilePush SDK configuration and are obtained from your MobilePush app.10 // See https://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/get-started/get-started-setupapps.html for more information.1112 // Use the builder method to configure the SDK for usage. This gives you the maximum flexibility in SDK configuration.13 // The builder lets you configure the SDK parameters at runtime.14 #if DEBUG1516 let appID = "[DEV-APNS App ID value from MobilePush app admin]"17 let accessToken = "[DEV-APNS Access Token value from MobilePush app admin]"18 let appEndpoint = "[DEV-APNS App Endpoint value from MobilePush app admin]"19 let mid = "[DEV-APNS account MID value from MobilePush app admin]"20 #else21 let appId = "[PROD-APNS appId value from MobilePush app admin]"22 let accessToken = "[PROD-APNS accessToken value from MobilePush app admin]"23 let appEndpoint = "[PROD-APNS app endpoint value from MobilePush app admin]"24 let mid = "[PROD-APNS account MID value from MobilePush app admin]"25 #endif262728 // Define features of MobilePush your app will use.29 let inbox = false30 let location = false31 let analytics = true3233 // MobilePush SDK: REQUIRED IMPLEMENTATION34 @discardableResult35 func configureMarketingCloudSDK() ->Bool{36 // Use the builder method to configure the SDK for usage. This gives you the maximum flexibility in SDK configuration.37 // The builder lets you configure the SDK parameters at runtime.38 let builder = MarketingCloudSDKConfigBuilder()39 .sfmc_setApplicationId(appID)40 .sfmc_setAccessToken(accessToken)41 .sfmc_setMarketingCloudServerUrl(appEndpoint)42 .sfmc_setMid(mid)43 .sfmc_setInboxEnabled(inbox as NSNumber)44 .sfmc_setLocationEnabled(location as NSNumber)45 .sfmc_setAnalyticsEnabled(analytics as NSNumber)46 .sfmc_build()!4748 var success = false4950 // Once you've created the builder, pass it to the sfmc_configure method.51 do{52 try MarketingCloudSDK.sharedInstance().sfmc_configure(with:builder)53 success = true54}catch let error as NSError{55 // Errors returned from configuration will be in the NSError parameter and can be used to determine56 // if you've implemented the SDK correctly.5758 let configErrorString = String(format: "MarketingCloudSDK sfmc_configure failed with error = %@", error)59 print(configErrorString)60}6162 if success == true{63 // The SDK has been fully configured and is ready for use!6465 // Enable logging for debugging. Not recommended for production apps, as significant data66 // about MobilePush will be logged to the console.67 #if DEBUG68 MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true)69 #endif70}7172 return success73}7475 // MobilePush SDK: REQUIRED IMPLEMENTATION76 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) ->Bool{77 return self.configureMarketingCloudSDK()78}7980 // MobilePush SDK: OPTIONAL IMPLEMENTATION (if using Data Protection)81 func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication){82 if(MarketingCloudSDK.sharedInstance().sfmc_isReady() == false)83{84 self.configureMarketingCloudSDK()85}86}87}
Enable or disable analytics, location, or inbox entries depending on the application’s needs and your usage of Marketing Cloud Engagement.
iOS Data Protection affects the SDK as described in this table.
iOS Data Protection Level
SDK Behavior
No protection
SDK works in the foreground and background
Complete until first user authentication
SDK works in the foreground and background after first unlock
Complete unless open
SDK works in the foreground and background after first unlock
Complete
SDK works only in the foreground after the device is unlocked
Extend the SDK configuration code outlined in Configure the SDK to add support for push registration.
If your app uses version 10 or higher of the SDK, use this code.
SDK for iOS, version 10 or higher
1// MobilePush SDK: REQUIRED IMPLEMENTATION2 func configureSdk() ->Bool{34 // Enable logging for debugging early on. Debug level is not recommended for production apps, as significant data5 // about the SDK will be logged to the console.6 #if DEBUG7 SFMCSdk.setLogger(logLevel: .debug)8 #endif910 // 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.1213 let pushFeatureConfiguration = PushFeatureConfigBuilder()14 .setApplicationControlsBadging(true)15 .build()1617 // Set the completion handler to take action when all modules initialization is completed.18 // Seting the completion handler is optional.1920 let completionHandler: ((_ status: [ModuleInitStatus]) ->Void) = {[weak self] status in21 DispatchQueue.main.async{22 self?.handleSDKInitializationCompletion(status: status)23}24}2526 SFMCSdk.initializeSdk(ConfigBuilder().setMAM(27 config: pushFeatureConfiguration).build(),28 completion: completionHandler29)3031 return true32}3334 // MARK: - SDK Initialization Completion Handler3536 private func handleSDKInitializationCompletion(status: [ModuleInitStatus]){37 var allSuccessful = true3839 for moduleStatus in status {40 print("Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)")4142 if moduleStatus.initStatus == .success {43 // Handle successful initialization for each module44 switch moduleStatus.moduleName {45 case .pushFeature:46 setupPushFeature()47 default:48 break49}50}else if moduleStatus.initStatus == .error{51 allSuccessful = false52 // module failed to initialize, check logs for more details53}else if moduleStatus.initStatus == .cancelled {54 allSuccessful = false55 // module initialization was cancelled (for example if the56 // re-configuration was triggered before initialization completed)57}else if moduleStatus.initStatus == .timeout {58 allSuccessful = false59 // module failed to initialize due to timeout, check logs for more details60}61}62 if allSuccessful {63 print("SDK initialization completed successfully")64}else{65 print("SDK initialization completed with errors - check logs above")66}67}6869 func setupPushFeature(){70 // Set the URLHandlingDelegate to handle URLs from CloudPage, OpenDirect,71 //Location, and Inbox messages. In this example, the AppDelegate class adheres72 // to the URLHandlingDelegate protocol (see below).73 PushFeature.requestSdk{ pushFeature in74 DispatchQueue.main.async{75 pushFeature?.setURLHandlingDelegate(self)76}77}78}7980 func application(81 _ application: UIApplication,82 didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?83) ->Bool{84 self.configureSdk()85 return true86}
If your app uses version 8 or 9 of the SDK, use this code.
SDK for iOS, version 8 and 9
1// SDK: REQUIRED IMPLEMENTATION2 func configureSDK(){3 #if DEBUG4 SFMCSdk.setLogger(logLevel: .debug)5 #endif67 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()1516 let completionHandler: (OperationResult) ->() = { result in17 if result == .success {18 self.setupMobilePush()19}20}2122 SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build())23}2425 func setupMobilePush(){2627 // 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 // For more information, see https://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/sdk-implementation/implementation-urlhandling.html31 SFMCSdk.requestPushSdk{ mp in32 mp.setURLHandlingDelegate(self)33}3435 // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will present UI.36 DispatchQueue.main.async{37 // Set the UNUserNotificationCenterDelegate to a class adhering to thie protocol.38 // In this exmple, the AppDelegate class adheres to the protocol (see below)39 // and handles Notification Center delegate methods from iOS.40 UNUserNotificationCenter.current().delegate = self4142 // Request authorization from the user for push notification alerts.43 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) ->Void in44 if error == nil{45 if granted == true{46 // Your application may want to do something specific if the user has granted authorization47 // for the notification types specified; it would be done here.48}49}50})5152 // In any case, your application should register for remote notifications *each time*53 // your application launches to ensure that the push token used by MobilePush (for silent push)54 // is updated if necessary.5556 // Registering in this manner does *not* mean that a user will see a notification - it only means57 // that the application will receive a unique push token from iOS.58 UIApplication.shared.registerForRemoteNotifications()59}60}
This code example shows how to configure the version 7 of the SDK for iOS apps.
SDK for iOS, version 7
1func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) ->Bool{23 // ... SDK configuration setup45 var success = false67 do{8 try MarketingCloudSDK.sharedInstance().sfmc_configure(with:builder)9 success = true10}catch let error as NSError{11 // Errors returned from configuration will be in the NSError parameter and can be used to determine12 // if you've implemented the SDK correctly.1314 let configErrorString = String(format: "MarketingCloudSDK sfmc_configure failed with error = %@", error)15 print(configErrorString)16}1718 if success == true{19 // The SDK has been fully configured and is ready for use!2021 // Enable logging for debugging. Not recommended for production apps, as significant data22 // about MobilePush will be logged to the console.23 #if DEBUG24 MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true)25 #endif2627 // Set the MarketingCloudSDKURLHandlingDelegate to a class adhering to the protocol.28 // In this example, the AppDelegate class adheres to the protocol29 // and handles URLs passed back from the SDK.30 // For more information, see https://salesforce-marketingcloud.github.io/MarketingCloudSDK-iOS/sdk-implementation/implementation-urlhandling.html31 MarketingCloudSDK.sharedInstance().sfmc_setURLHandlingDelegate(self)3233 // Make sure to dispatch this to the main thread, as UNUserNotificationCenter will present UI.34 DispatchQueue.main.async{35 if #available(iOS 10.0, *){36 // Set the UNUserNotificationCenterDelegate to a class adhering to thie protocol.37 // In this exmple, the AppDelegate class adheres to the protocol (see below)38 // and handles Notification Center delegate methods from iOS.39 UNUserNotificationCenter.current().delegate = self4041 // Request authorization from the user for push notification alerts.42 UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {(_ granted: Bool, _ error: Error?) ->Void in43 if error == nil{44 if granted == true{45 // Your application may want to do something specific46 // if the user has granted authorization for the47 // notification types specified; it would be done here.48 print(MarketingCloudSDK.sharedInstance().sfmc_deviceToken() ?? "error: no token - was UIApplication.shared.registerForRemoteNotifications() called?")49}50}51})52}5354 // In any case, your application should register for remote notifications *each time*55 // your application launches to ensure that the push token used by MobilePush (for silent push) is updated if necessary.5657 // Registering in this manner does *not* mean that a user will see a notification,58 // it only means that the application will receive a unique push token from iOS.59 UIApplication.shared.registerForRemoteNotifications()60}61}6263 return true64}
Add the required UIApplicationDelegate protocol methods to support push registration to your AppDelegate class. This code example shows how to configure the version 8 and later of the SDK for iOS apps.
If your app uses version 10 or higher of the SDK, use this code.
SDK for iOS, version 10 or higher
1// PushFeature SDK: REQUIRED IMPLEMENTATION2func application(_ application: UIApplication,3 didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){4 PushFeature.requestSdk{ pushFeature in5 pushFeature?.setDeviceToken(deviceToken)6}7}89// PushFeature SDK: REQUIRED IMPLEMENTATION10func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error){11 print(error)12}1314// PushFeature SDK: REQUIRED IMPLEMENTATION15/**16This delegate method lets apps with the "remote-notification" background mode17fetch data in response to an incoming remote notification.1819Call the fetchCompletionHandler as soon as you're finished performing that20operation so the system can accurately estimate its power and data cost.2122This method is invoked even if the application was launched or resumed because23of the remote notification. The delegate methods are invoked first.2425This 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 in33 pushFeature?.setNotificationUserInfo(userInfo)34}35 completionHandler(.newData)36}
If your app uses version 8 or 9 of the SDK, use this code.
SDK for iOS, version 8 or 9
1// MobilePush SDK: REQUIRED IMPLEMENTATION2 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){3 SFMCSdk.requestPushSdk{ mp in4 mp.setDeviceToken(deviceToken)5}6}78 // MobilePush SDK: REQUIRED IMPLEMENTATION9 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error){10 print(error)11}1213 // MobilePush SDK: REQUIRED IMPLEMENTATION14 /** 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 in22 mp.setNotificationUserInfo(userInfo)23}24 completionHandler(.newData)25}
This code example shows how to configure the version 7 and earlier of the SDK for iOS apps.
SDK for iOS, version 7
1// MobilePush SDK: REQUIRED IMPLEMENTATION2 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){3 MarketingCloudSDK.sharedInstance().sfmc_setDeviceToken(deviceToken)4}56 // MobilePush SDK: REQUIRED IMPLEMENTATION7 func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error){8 print(error)9}1011 // MobilePush SDK: REQUIRED IMPLEMENTATION12 /** 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}
Add the required UNUserNotificationCenterDelegate protocol methods to support push notifications to your AppDelegate class.
If your app uses version 10 or higher of the SDK, use this code.
SDK for iOS, version 10 or higher
1/// The method is called on the delegate when the user responds to the notification2 /// by opening the application, dismissing the notification or choosing a3 /// UNNotificationAction. The delegate must be set before the application returns4 /// from applicationDidFinishLaunching:.5 /// *6 func userNotificationCenter(7 _ center: UNUserNotificationCenter,8 didReceive response: UNNotificationResponse,9 withCompletionHandler completionHandler: @escaping() ->Void10){11 // Required: Tell theSDK about the notification so that it begins to12 // collect analytics and process the notification for your app.13 PushFeature.requestSdk{ pushFeature in14 pushFeature?.setNotificationResponse(response)15}16 completionHandler()17}1819 /// The method is called on the delegate only if the application is in the20 /// foreground. If the method isn't implemented or the handler isn't called in a21 /// timely manner, then the notification isn't shown. The application can22 /// have the notification presented as a sound, badge, alert, or it can appear23 /// in the notification list. This decision should be based on whether the24 /// 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 UNNotificationPresentationOptions31) ->Void32){33 completionHandler(.alert)34}
If your app uses version 9 of the SDK, use this code.
SDK for iOS, version 9
1// MobilePush SDK: REQUIRED IMPLEMENTATION2// 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 analytics8 // and process the notification on behalf of your application.9 SFMCSdk.requestPushSdk{ mp in10 mp.setNotificationResponse(response)11}12 completionHandler()13}1415// MobilePush SDK: REQUIRED IMPLEMENTATION16// 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}
If your app uses version 8 of the SDK, use this code.
SDK for iOS, version 8
1// MobilePush SDK: REQUIRED IMPLEMENTATION2// 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 analytics8 // and process the notification on behalf of your application.9 SFMCSdk.requestPushSdk{ mp in10 mp.setNotificationRequest(response.notification.request)11}12 completionHandler()13}1415// MobilePush SDK: REQUIRED IMPLEMENTATION16// 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}
If your app uses version 7 of the SDK, use this code.
SDK for iOS, version 7
1// MobilePush SDK: REQUIRED IMPLEMENTATION2// 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}1213// MobilePush SDK: REQUIRED IMPLEMENTATION14// 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 methods described in this procedure use MarketingCloud SDK APIs to facilitate the framework’s functionality to manage push notifications, which include contact registration and push analytics tracking. If you implement the methods without using the MarketingCloud SDK methods, these features don’t work as expected.