Configure the SDK for iOS

After you install the SDK dependencies manually, with CocoaPods, or with Swift Package Manager, configure the SDK using the ConfigBuilder method.

Earlier versions of the SDK supported JSON file configuration, which is deprecated. If your implementation uses JSON configuration, reconfigure it using the builder method.

Note

Use these code examples to configure the SDK in your app. Make these changes to the examples:

  • Add the Access Token, App ID, App Endpoint, and MID values that you obtained when you configured Marketing Cloud Engagement.
  • Enable or disable analytics, location, or inbox based on your app’s requirements.

Also, consider the ways that iOS Data Protection impact your app.

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

1import MarketingCloudSDK
2import SFMCSDK
3import UIKit
4
5@main
6class AppDelegate: UIResponder, UIApplicationDelegate {
7
8  var window: UIWindow?
9
10  // Marketing Cloud SDK configuration
11  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>"
15
16  // Define features of Marketing Cloud your app uses
17  let mcInboxEnabled = false
18  let mcLocationEnabled = false
19  let mcAnalyticsEnabled = true
20
21  // MarketingCloud SDK: REQUIRED IMPLEMENTATION
22  @discardableResult
23
24  func configureSdk() -> Bool {
25
26    // Enable logging for debugging. Don't use debug level in production apps because the SDK logs
27    // significant data to the console.
28
29    #if DEBUG
30      SFMCSdk.setLogger(logLevel: .debug)
31    #endif
32
33    // Use the `MarketingCloudSdkConfigBuilder` to configure the MarketingCloud SDK.
34    // The builder lets you configure the module parameters at runtime.
35
36    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()
44
45    // Set the completion handler to take action when module initialization completes.
46    // Setting the completion handler is optional.
47
48    let completionHandler: ((_ status: [ModuleInitStatus]) -> Void) = { [weak self] status in
49      DispatchQueue.main.async {
50        self?.handleSDKInitializationCompletion(status: status)
51      }
52    }
53
54    SFMCSdk.initializeSdk(
55      ConfigBuilder().setEngagement(config: engagementConfiguration).build(),
56      completion: completionHandler)
57
58    return true
59  }
60
61  // MARK: - SDK Initialization Completion Handler
62
63  private func handleSDKInitializationCompletion(status: [ModuleInitStatus]) {
64    var allSuccessful = true
65
66    for moduleStatus in status {
67      print(
68        "Module: \(moduleStatus.moduleName.rawValue), Status: \(moduleStatus.initStatus.rawValue)")
69
70      if moduleStatus.initStatus == .success {
71        // Handle successful initialization for each module
72        switch moduleStatus.moduleName {
73        case .engagement:
74          // Handle successful initialization for Marketing Cloud module
75        default:
76          break
77        }
78      } else if moduleStatus.initStatus == .error {
79        allSuccessful = false
80        // Module failed to initialize. Check logs for details.
81      } else if moduleStatus.initStatus == .cancelled {
82        allSuccessful = false
83        // Module initialization was cancelled. For example, reconfiguration was triggered before initialization completed.
84      } else if moduleStatus.initStatus == .timeout {
85        allSuccessful = false
86        // Module failed to initialize due to timeout. Check logs for details.
87      }
88    }
89    if allSuccessful {
90      print("SDK initialization completed successfully")
91    } else {
92      print("SDK initialization completed with errors - check logs above")
93    }
94  }
95
96  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 true
103  }
104
105  // 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.

1import SFMCSDK
2import MarketingCloudSDK
3
4class AppDelegate: UIResponder, UIApplicationDelegate {
5
6  var window: UIWindow?
7
8  // SDK: REQUIRED IMPLEMENTATION
9
10  // The appID, accessToken, and appEndpoint are required configuration values.
11  #if DEBUG
12    let appId = YOUR_DEV_APP_ID
13    let accessToken = YOUR_DEV_ACCESS_TOKEN
14    let appEndpoint = YOUR_DEV_APP_ENDPOINT
15    let mid = YOUR_DEV_MID
16  #else
17    let appId = YOUR_PROD_APP_ID
18    let accessToken = YOUR_PROD_ACCESS_TOKEN
19    let appEndpoint = YOUR_PROD_APP_ENDPOINT
20    let mid = YOUR_PROD_MID
21  #endif
22
23
24  // Define the features your app uses
25  let inbox = false
26  let location = false
27  let analytics = true
28
29  // SDK: REQUIRED IMPLEMENTATION
30  func configureSDK() {
31    // Enable logging for debugging. Don't use debug level in production apps because the SDK logs
32    // a large amount of data to the console.
33    #if DEBUG
34    SFMCSdk.setLogger(logLevel: .debug)
35    #endif
36
37    // Use the Config Builder to configure the module parameters at runtime.
38    let mobilePushConfiguration = PushConfigBuilder(appId: appId)
39      .setAccessToken(accessToken)
40      .setMarketingCloudServerUrl(appEndpoint)
41      .setMid(mid)
42      .setInboxEnabled(inbox)
43      .setLocationEnabled(location)
44      .setAnalyticsEnabled(analytics)
45      .build()
46
47    // Set the completion handler to take action when module initialization completes. The result indicates whether initialization was successful.
48    // Setting the completion handler is optional.
49    let completionHandler: (OperationResult) -> () = { result in
50      if result == .success {
51        // Module is fully configured and ready for use
52      } else if result == .error {
53        // Module failed to initialize. Check logs for details.
54      } else if result == .cancelled {
55        // Module initialization was cancelled. For example, reconfiguration was triggered before initialization completed.
56      } else if result == .timeout {
57        // Module failed to initialize due to timeout. Check logs for details.
58      }
59    }
60
61    // After you create the configuration, initialize the SDK.
62    SFMCSdk.initializeSdk(ConfigBuilder().setPush(config: mobilePushConfiguration, onCompletion: completionHandler).build())
63  }
64
65  // SDK: REQUIRED IMPLEMENTATION
66  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
67    self.configureSDK()
68
69    return true
70  }
71
72  // SDK: OPTIONAL IMPLEMENTATION (if using Data Protection)
73  func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) {
74    if (SFMCSdk.mp.getStatus() != .operational) {
75      self.configureSFMCSdk()
76    }
77  }
78}

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

1import MarketingCloudSDK
2
3class AppDelegate: UIResponder, UIApplicationDelegate {
4
5  var window: UIWindow?
6
7  // REQUIRED IMPLEMENTATION
8
9  // The appID, accessToken, and appEndpoint are required configuration values.
10
11  // Use the builder method to configure the SDK.
12  // The builder lets you configure the SDK parameters at runtime.
13  #if DEBUG
14
15  let appID = YOUR_DEV_APP_ID
16  let accessToken = YOUR_DEV_ACCESS_TOKEN
17  let appEndpoint = YOUR_DEV_APP_ENDPOINT
18  let mid = YOUR_DEV_MID
19  #else
20  let appId = YOUR_PROD_APP_ID
21  let accessToken = YOUR_PROD_ACCESS_TOKEN
22  let appEndpoint = YOUR_PROD_APP_ENDPOINT
23  let mid = YOUR_PROD_MID
24  #endif
25
26
27  // Define the features your app uses
28  let inbox = false
29  let location = false
30  let analytics = true
31
32  // REQUIRED IMPLEMENTATION
33  @discardableResult
34  func configureMarketingCloudSDK() -> Bool {
35    // Use the builder method to configure the SDK.
36    // The builder lets you configure the SDK parameters at runtime.
37    let builder = MarketingCloudSDKConfigBuilder()
38      .sfmc_setApplicationId(appID)
39      .sfmc_setAccessToken(accessToken)
40      .sfmc_setMarketingCloudServerUrl(appEndpoint)
41      .sfmc_setMid(mid)
42      .sfmc_setInboxEnabled(inbox as NSNumber)
43      .sfmc_setLocationEnabled(location as NSNumber)
44      .sfmc_setAnalyticsEnabled(analytics as NSNumber)
45      .sfmc_build()!
46
47    var success = false
48
49    // After you create the builder, pass it to the sfmc_configure method.
50    do {
51      try MarketingCloudSDK.sharedInstance().sfmc_configure(with:builder)
52      success = true
53    } catch let error as NSError {
54      // Configuration errors are returned in the NSError parameter. Use them to determine
55      // whether you implemented the SDK correctly.
56
57      let configErrorString = String(format: "MarketingCloudSDK sfmc_configure failed with error = %@", error)
58      print(configErrorString)
59    }
60
61    if success == true {
62      // The SDK is fully configured and ready for use.
63
64      // Enable logging for debugging. Don't use this in production apps because the SDK logs
65      // a large amount of data to the console.
66      #if DEBUG
67      MarketingCloudSDK.sharedInstance().sfmc_setDebugLoggingEnabled(true)
68      #endif
69    }
70
71    return success
72  }
73
74  // REQUIRED IMPLEMENTATION
75  func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
76    return self.configureMarketingCloudSDK()
77  }
78
79  // OPTIONAL IMPLEMENTATION (if using Data Protection)
80  func applicationProtectedDataDidBecomeAvailable(_ application: UIApplication) {
81    if(MarketingCloudSDK.sharedInstance().sfmc_isReady() == false)
82    {
83      self.configureMarketingCloudSDK()
84    }
85  }
86}

Data Protection Considerations 

iOS Data Protection encrypts files stored on the device and controls when your app can access them based on the lock state of the user’s device. If your app uses Data Protection, you must configure the SDK at the right time to ensure it can access the encrypted data it needs to function. The SDK’s ability to work in the foreground or background depends on the Data Protection level you configure.

iOS Data Protection affects the SDK in these ways.

iOS Data Protection LevelSDK Behavior
No protectionSDK works in the foreground and background
Complete until first user authenticationSDK works in the foreground and background after first unlock
Complete unless openSDK works in the foreground and background after first unlock
CompleteSDK works only in the foreground after the device is unlocked

For more information, see iOS Data Protection.

See Also