Overview

Skill Level: Intermediate

This tutorial explains how to configure mobile app messages in iOS apps that are developed with Swift.

WARNING: When IBM Mobile App Messaging stores data that you send, the data is not encrypted. IBM Mobile App Messaging recommends that you do not transmit sensitive information in inbox, inapp, and mobile app messages. We do not encrypt the data in our databases or log files, or when stored on the device. If you must transmit sensitive information, encrypt the data before sending it and decrypt the data in memory on the device.

Prerequisites

To get started, you need:

  • Membership in the iOS Developer Program.

TIP: If you are not an iOS developer, find out who manages the Apple Developer Program for your organization.

  • Account with Watson Campaign Automation.

TIP: If you do not already have an Watson Campaign Automation account, contact your Client Services representative or sales.

  • To register your iOS app with Apple. For instructions, see Setting up iOS apps in Apple.
  • To add your iOS app to Watson Campaign Automation. For instructions, see Adding an app in Watson Campaign Automation.

    RESTRICTION: Watson Campaign Automation documentation contains information for marketers, app developers, and organization administrators and requires a user name and password. If you need a user name and password, contact your Client Services representative.

  • The latest stable version of the IBM Mobile App Messaging SDK for iOS at https://github.com/ibm-mobile-push/ios.

    NOTE: SDK versions before v3.6.1.0 do not support Swift Application Delegates. As a workaround, you can use an Objective-C delegate class. For an example, see the sample Swift project that is provided in the Mobile App Messaging SDK v3.6.1.0 (and later).

  • An app that is compliant with Automatic Reference Counting (ARC). To enable ARC in your Xcode project, go to Target > Build Phases > Compile Source, select the files in the Plugins folder, and add -fobjc-arc.
  • Information about supported platforms, sample app compatibility, and what’s new in the latest version of the IBM Mobile App Messaging SDK for iOS. See Supported platforms and sample app compatibility and What’s new in mobile app messaging.
  • Information about where to find Mobile App Messaging documentation. See Where to find IBM Mobile App Messaging documentation.
  • Migrate to the latest Swift version by clicking Edit Menu > Migrate > Current Swift Syntax.

    This changes main.swift.

    For Swift 4.2:

    
    import Foundation
     import UIKit
     import IBMMobilePush
    let _ = UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(MCEAppDelegate.self) )
    

    For Swift 4.1:

    import Foundation
     import UIKit
    import IBMMobilePush
    let argv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer.self, capacity: Int(CommandLine.argc))
    let _ = UIApplicationMain(CommandLine.argc, argv, nil, NSStringFromClass(MCEAppDelegate.self) )
    

 

Remember: Before you begin your development with the IBM Mobile App Messaging SDK for iOS, you must install the iOS development tools and have an iOS provisioning file to develop iOS applications. The following tutorial assumes you are familiar with the iOS development process.

 

Are you working with Objective C?

If you are working with Objective C, follow the instructions in Getting started with mobile app messages in iOS apps developed with Objective C.

Step-by-step

  1. Build the sample application that is provided in the SDK.

    The IBM Mobile App Messaging SDK for iOS includes a sample application that helps demonstrate end-to-end functions in mobile app messages. You use the sample app included in the SDK to learn how to build a mobile app message and to discover capabilities that are available. For instructions about building the sample application, see Setting up the sample app that is included in the Mobile App Messaging SDK for iOS.

  2. Integrate the IBM Mobile App Messaging SDK with your iOS app.

    RESTRICTION: Before you can implement the IBM Mobile App Messaging SDK for iOS, you must download and extract the latest version of the iOS SDK as described in the Prerequisties.

    To implement the IBM Mobile App Messaging SDK for iOS:

    1. Install the IBM Mobile App Messaging SDK for iOS into your app. You can manually add the IBM Mobile App Messaging framework to your application, or you can add the framework by using the CocoaPods dependency manager.

       

      Manually linking frameworks and libraries
      To manually link frameworks and libraries with your project’s object files and produce a binary file, follow these steps:

      1. Copy IBMMobilePush.framework to your project’s frameworks.
      2. Copy MceConfig.json to your project.
      3. Select the target in the project editor, and copy the following frameworks (including dependencies) to your project in the Linked Frameworks and Libraries section.
        • libz.tbd
        • CoreLocation.framework
        • libsqlite3.0.tbd
        • CoreData.framework
        • CoreTelephony.framework

          (If you see these frameworks in the section, you can skip adding them.)

      4. Add -ObjC to the Other Linker Flags build options.
      5. Set your team in the General tab and the provisioning profile in the Build Settings tab.
        You must set your team and provisioning profile before the app has permission to get the APNs deviceToken.
      6. Copy the main.swift file to your project. For informaton about the main.swift file, see the Prerequisites.

       

      Using CocoaPods to add the framework
      To add the IBM Mobile App Messaging framework by using the CococaPods dependency manager, follow these steps:

      1. Install CocoaPods and add the pod for the SDK to your podfile:
        pod 'IBMMobilePush', :git => 'https://github.com/ibm-mobile-push/ios.git', :tag => '3.7.1.2.3'
        
      2. Add -ObjC to the Other Linker Flags build options.
      3. Set your team in the General tab and the provisioning profile in the Build Settings tab. You must set your team and provisioning profile before the app has permission to get the APNs deviceToken.
      4. For the pod target and the app target, go to the Build Settings tab and set Set Build Active Architectures Only to No for both Debug and Release.
      5. Set Push Notification capability in Target Capabilities.
    2. Configure the MceConfig.json.

      Note: If you want to implement the iOS SDK without using the MceConfig.json file, you can use a NSDictionary object. To use a NSDictionary object, skip the MceConfig.json file configuration that is described in this step, perform the manual integration that is described in step 3, and then modify the application:didFinishLaunchingWithOptions: method in your application delegate. For more information, see Initializing the SDK with a NSDictionary object.

      To configure MceConfig.json, open the file and modify the following fields:

      • baseURL – provide the base URL for your Pod. For more information, see Setting the baseURL.
      • appKey – in the dev and prod fields, provide the development app keys and production app keys that were generated in IBM Watson Campaign Automation. Depending on how the app is compiled, the SDK can choose the correct app key to use. Do not change your app key after you publish your app.
      • appDelegateClass – replace AppDelegate with your AppDelegate class name. For Swift apps, you must add the product name as a prefix to the appDelegate class name. For example, for the Swift sample app that is included in the SDK Package, you add:
        "appDelegateClass": "SwiftSample.AppDelegate",
        
      • loglevel – provide a log level for debugging mode and production mode. For debugging mode, set to verbose and for production mode, set to error. For information, see Setting log level messages types.
      • additional settings for Logging:
        ¬†¬†¬†¬† – “maximumSize” – maximum number of bytes for log files before they’re rotated, default value is 10MB
        ¬†¬†¬†¬† – “maximumNumberOfLogFiles” – maximum number of rotated log files, default value is 7

        Note: For information about other properties in the MceConfig.json, see these topics:

    3. Perform one of the following types of integrations: 

      Easy integration – The easy integration simplifies communication between the OS and required integration points by replacing the application delegate object with one that processes incoming push message data and forwards all calls back to your application delegate. In most cases, IBM recommends that you perform the easy integration.

      Manual integration – The manual integration allows for additional control by calling into the MCE SDK at various integration points in your application delegate. Perform a manual integration only in special cases. For example, perform a manual integration if you have another app that needs to be app delegate or if you are using a NSDictionary object to initialize the SDK. For instructions about performing a manual integration, see Manually integrating the iOS SDK using Swift.

      To perform the easy integration, follow these steps.

      1. Add the following import directive to the top of the Swift AppDelegate file:

        @import UserNotifications;
        
      2. Remove the @UIApplicationMain decorator from the Swift AppDelegate file.
      3. Remove the following method from the Swift AppDelegate file:
        For Swift 4.1

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
         [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool
        

        For Swift 4.2 (Notice the period in UIApplication.LaunchOptionsKey)

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool
        
      4. Add the following code to the application: didFinishLaunchingWithOptions: method in your AppDelegate .m class. This code sets the notification type to badge, sound, and alert. If you do not require all of these notification types, remove it from each declaration for each OS support level.
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool
        {
        
            if #available(iOS 10.0, *) {
                 application.registerForRemoteNotifications()
        
                // iOS 10+ Example static action category:
                let acceptAction = UNNotificationAction(identifier: "Accept", title: "Accept", options: [.foreground])
                let rejectAction = UNNotificationAction(identifier: "Reject", title: "Reject", options: [.destructive])
                let category = UNNotificationCategory(identifier: "example", actions: [acceptAction, rejectAction], intentIdentifiers: [], options: [.customDismissAction])
                
                var categories = Set()
                categories.insert(category)
                
                // iOS 10+ Push Message Registration
                let center = UNUserNotificationCenter.current()
                center.delegate=MCENotificationDelegate.sharedInstance()
                center.requestAuthorization(options: [.alert, .sound, .carPlay, .badge], completionHandler: { (granted, error) in
                    if let error = error {
                        print("Could not request authorization from APNS \(error.localizedDescription)")
                    }
                    center.setNotificationCategories(categories)
                })
            }
        
            else if #available(iOS 8.0, *) {
                // iOS 8+ Example static action category:
                let acceptAction = UIMutableUserNotificationAction()
                acceptAction.identifier = "Accept"
                acceptAction.title = "Accept"
                acceptAction.isDestructive=false
                acceptAction.isAuthenticationRequired=false
                
                let rejectAction = UIMutableUserNotificationAction()
                rejectAction.identifier = "Reject"
                rejectAction.title = "Reject"
                rejectAction.isDestructive=true
                rejectAction.isAuthenticationRequired=false
                
                let category = UIMutableUserNotificationCategory()
                category.identifier="example"
                category.setActions([acceptAction, rejectAction], for: .default)
                category.setActions([acceptAction, rejectAction], for: .minimal)
                
                // iOS 8+ Push Message Registration
                let settings = UIUserNotificationSettings(types: [.badge, .sound, .alert], categories: [category])
                application.registerUserNotificationSettings(settings)
                application.registerForRemoteNotifications()
            } else {
                // iOS < 8 Push Message Registration
                application.registerForRemoteNotifications(matching: [.badge, .alert, .sound])
            }
        
            return true
        } 
        
  3. Customize mobile app messages by implementing advanced features.

    After you integrate the IBM Mobile App Messaging SDK with your iOS app and have basic mobile app messaging operational, you can customize your build with advanced options. The following tutorials provide end-to-end instructions about implementing mobile app messaging features in your iOS apps:

  4. What to do next…

    After you integrate the IBM Mobile App Messaging SDK with your iOS app, you prepare your iOS app for App Store distribution. For instructions, see Preparing your iOS app for App Store distribution.

    Finally, after developers complete the steps described in this tutorial, marketers use Watson Campaign Automation to create, schedule and send mobile app messages. For more information, see Create, schedule, and send mobile app messagines in Watson Campaign Automation.

Expected outcome

This tutorial takes you through the basic steps to configure mobile app messages for iOS apps. For more information about mobile app messaging, see the Documentation.

Go Back to Mobile Application Messaging home page.

Join The Discussion

Your email address will not be published. Required fields are marked *