Add the iOS SDK to your app

Overview

You can integrate the iOS SDK with your iOS apps developed with Swift and Objective-C.

Before you begin

  • Create an Apple ID and password.
  • Create an iPhone app key on the Campaign Automation console. Then, upload the APNS certificate.
  • Add your iOS app to Acoustic Campaign. For more information, see Add and configure mobile developer apps.

Register your app with Apple

  1. Enable push notifications in your XCode project (iOS 10 only).
    a. Go to Target sample in your XCode project.
    b. Select the Capabilities tab, and then enable Push Notifications.

  2. Ensure that your iOS application contains a bridging header (Swift only).
    The bridging header must contain #import <AcousticMobilePush/AcousticMobilePush.h>. For more information, see Swift.

  3. Set up App Keys or a push certificate in the Apple developer center.
    Apple Push Notification Services (APNS) allows an app to notify users when it is not running in the foreground. You must register to connect to the APNS and send mobile app messages to devices. Register with the APNS by providing an explicit app ID. You cannot use a wildcard App ID.

When you generate an explicit app ID, you can use one of the following valid forms of authentication:
P8 SSL signing key
If you use the P8 SSL signing key, you can send mobile app messages to all the applications in your Apple org. You can send the messages because you can create separate App Keys for the applications.

a) To create an app key, you need an explicit bundle ID and the team ID representing the Apple org. You can get the team ID from your Apple account membership page.
b) Generate a P8 file and provide this file when creating the app key.
c) Open Apple account, click Certificates, Identifiers & Profiles.
d) Then navigate to the All Keys page.
e) Click the Add (+) icon and select the APNS checkbox and proceed through the steps.
f) The Apple website generates a p8 file. For example, APNsAuthKey_XXXXXXXXXXX.p8, where the X's represent the App Key. You can find the file and the App Key on the App Key creation page.

P12 SSL certification
You enable mobile app messages when you create or edit an explicit app ID. Mobile app messages are not entirely enabled until client SSL certification is generated. A client SSL certificate allows your notification server to connect to the APNS. Each App ID is required to have its client SSL certificate.
To configure APNS, go to Apple account, and then follow these steps:

a) Go to Certificates, Identifiers & Profiles > Identifiers.
b) Locate the app ID that you want to use with the APNS. You can only use app IDs with a specific bundle ID with the APNS. You cannot use a wildcard app ID. A bundle ID is a specific identifier for a single app and must be unique to your app.
c) Click Edit next to the appropriate app ID.
d) Scroll down and select the Push Notifications check box.
e) Click Create Certificate for the type of SSL certificate you want to create. You can choose development or production.
f) Complete the guided steps to create the specific client SSL certificate for your app ID.
g) Download the client SSL certificate file and click Done.
h) Go to the folder where you downloaded the certificate file.
i) Double-click the file to install it in your keychain. The application creates an entry called Apple Development Push Services:<identifier>.
j) Expand to find the private key (your name or your corporate name) as a child beneath the push service.
k) Right-click and export the certificate and the private key in .p12 format. As part of the export, you must provide a password for this file.
l) You can verify your app ID settings on the app ID page. Check the development column or the distribution column depending on the client SSL certificate type. When the app ID is enabled, you will notice a green circle followed by Enabled in the push notifications row. A yellow circle followed by Configurable indicates a missing client SSL certificate.

  1. Set up a new provisioning profile that is based on your new APN-enabled app ID. The profile is set up to receive test notifications. For information, see provisioning profiles.

    a) Go to Certificates, Identifiers & Profiles > Provisioning Profiles.
    b) Click the Add (+) icon.
    c) Select iOS App Development or Mac App Development as the distribution method.
    d) Select the app ID you want to use for development.
    e) Select one or more development certificates.
    f) Select one or more devices.
    g) Enter a profile name.
    h) Download the development or distribution provisioning profiles.
    i) You can now find the profiles in the Code Signing Identity for both your Target and Project settings.
    j) Select the correct profile for either Development or Distribution.
    k) Go to Build Settings > Code Signing Identity.
    l) Verify that the correct provisioning profile is selected for your bundle ID.

📘

Note:

The provisioning profile that you create must match the push certificate. For example, a development provisioning profile works with a development push certificate. Similarly, there are two production distribution profiles: ad hoc and App Store. These provisioning profiles work only with production push certificates. The provisioning profile is bundled with your app and includes the push entitlement. The push entitlement asks the user for permission to send mobile app messages when the app is opened.

Download and add the SDK to your project

The Acoustic Mobile Push SDK contains three distinct frameworks that you may implement:

AcousticMobilePush.xcframework – This is the core mobile push SDK that supports our mobile push service.

AcousticMobilePushNotification.xcframework – This framework provides support for dynamic multi-action pushes and media attachments. If you need support for sending images, sound, and video attachments with your pushes, you must implement this framework. For more information, see Add the iOS Notification Service Framework to your project.

AcousticMobilePushWatch.xcframework - If you require Apple Watch support, you must implement this framework. For more information, see Create Apple Watch notifications.

You can add the iOS SDK to your app using the CocoaPods dependency manager.

  1. Create a Podfile in your Xcode project directory if you have not already.

  2. Open the Podfile in a text editor and make the following changes: 

    1. Add the following lines:

      source '<https://github.com/CocoaPods/Specs.git>'
    2. Set the platform as iOS 12.1: platform: ios, '12.1.

    3. Uncomment use_frameworks!

    4. In the respective targets, add the SDK as follows: 

      • If you want to use AcousticMobilePush SDK's release version:

        pod 'AcousticMobilePush' pod 'AcousticMobilePushNotification'

        If iWatch is used, add an iWatch extension

        pod 'AcousticMobilePushWatch'
      • If you want to use AcousticMobilePush SDK's debug version:

        pod 'AcousticMobilePushDebug' pod 'AcousticMobilePushNotificationDebug'

        If iWatch is used, add iWatch extension:

        pod 'AcousticMobilePushWatchDebug'

        By default, the sample application uses a debug version of libraries.

        📘

        Note:

        You can only use the release version or debug version. Do not use both at the same time.

  3. Run the command pod install to install the SDK in your project. To update the SDK, run pod update.

The pod install or pod update commands should complete without errors. Run the same command with the --verbose option if errors occur and share the error log with Acoustic support.

You can add the iOS SDK to your app using the Carthage dependency manager.

  1. Create a Cartfile in your Xcode project directory if you have not already.

  2. Open the Cartfile in a text editor and add the following: 

    • If you want to use AcousticMobilePush SDK's release version - 

      binary " <https://raw.githubusercontent.com/go-acoustic/Acoustic-Mobile-Push-iOS/master/AcousticMobilePush.json>" >= 3.8.18 binary " <https://raw.githubusercontent.com/go-acoustic/Acoustic-Mobile-Push-iOS/master/AcousticMobilePushNotification.json>" >= 3.8.18 binary " <https://raw.githubusercontent.com/go-acoustic/Acoustic-Mobile-Push-iOS/master/AcousticMobilePushWatch.json>" >= 3.8.18
    • If you want to use Tealeaf SDK's debug version -

      binary " <https://raw.githubusercontent.com/go-acoustic/Acoustic-Mobile-Push-iOS/master/AcousticMobilePushDebug.json>" >= 3.8.18 binary " <https://raw.githubusercontent.com/go-acoustic/Acoustic-Mobile-Push-iOS/master/AcousticMobilePushNotificationDebug.json>" >= 3.8.18 binary " <https://raw.githubusercontent.com/go-acoustic/Acoustic-Mobile-Push-iOS/master/AcousticMobilePushWatchDebug.json>" >= 3.8.18

      By default, the sample application uses a debug version of libraries.

      📘

      Note:

      You can only use the release version or debug version. Do not use both at the same time.

  1. Install Carthage by running the following command:

    carthage update --use-xcframeworks

    The Carthage command should complete without errors, and the Carthage build folder is created in your directory with all the SDK files.

  1. Add Carthage to your XCode target> General tab > Frameworks, Libraries, and Embedded Content section.
  2. Then, update the New Run Script Phase from the Build Phases tab of your target to copy the frameworks.

You can add the iOS SDK as a Switch package dependency to your Xcode project.

📘

Note:

You must have Xcode 12.x that supports Swift Packages.

Complete the following steps to add the AcousticMobilePush_iOS swift package.

  1. In your Xcode project, click File >Add Packages.

  2. Add the following Swift package URL in the Swift Packages repository screen and click Add Package.

    • If you want to use the release version -

      <https://github.com/go-acoustic/AcousticMobilePush-SP> <https://github.com/go-acoustic/AcousticMobilePushNotification-SP> <https://github.com/go-acoustic/AcousticMobilePushWatch-SP>
    • if you want to use the debug version -

      <https://github.com/go-acoustic/AcousticMobilePushDebug-SP> <https://github.com/go-acoustic/AcousticMobilePushNotificationDebug-SP> <https://github.com/go-acoustic/AcousticMobilePushWatchDebug-SP>

      📘

      Note:

      You can only use the release version or debug version. Do not use both at the same time.

  3. In the Project > Package Dependencies, the AcousticMobilePush_iOS swift packages will be available.

  1. Download the latest version of the iOS SDK and access the iOS Native APIs references and plug-ins.
  2. Set up each of the libraries as dependencies in your project.

📘

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 provided in the mobile app messaging SDK v3.6.1.0 (and later).

Integrate the iOS SDK to your app

You can integrate the iOS SDK into your app through automated integration or manual integration.
Automated integration – Integrating the SDK with your app using the automated integration is easy and allows for easy upgrading too. The SDK is integrated with your app by replacing the AppDelegate. This method simplifies communication between the OS and required integration points. The AppDelegate object is replaced with an object that processes incoming message data. That object then forwards all calls back to your AppDelegate.
Manual integration – The manual integration calls the SDK at various integration points in your AppDelegate. This method provides additional control but is recommended only in special cases. For example, perform a manual integration in the following scenarios:

  • When you have another library that requires the app delegate replaced. For example, Firebase or Facebook.
  • If you want to use an NSDictionary object to initialize the SDK.

📘

Note:

Do a manual integration if you do not want to rely on the AppDelegate replacement method. Acoustic recommends that you do not perform the manual integration unless necessary. The manual integration method requires more maintenance as you must ensure that all the support code is correct and kept up to date. Our automatic integration handles all of this for you. Some examples of when the manual integration method is needed include:

  1. Integrating Facebook support
  2. Implementing a second push provider source.
  1. If you did not use Cocoapods then ensure that AcousticMobilePush.xcframework is listed in your main application target's Frameworks, Libraries, and Embedded Content section of the General tab inside your project's configuration.
  2. If you did not use the NSDictionary then download the MceConfig file and add it to all your application's project's targets. For more information about MceConfig, see Configuration (MceConfig.json).
  3. If you are not using the NSDictionary then modify MceConfig.json to include your app keys.
  4. Set your team and provisiioning profile in the Signing and Capabilities tab. You must complete this step before the app has permission to get the APNs deviceToken.
  5. For the pod target and the app target, go to the Build Settings tab and set Set Build Active Architectures Only to No. You must set it to No for both Debug and Release.
  6. Set Push Notification capability in Target Capabilities.
  7. Add App Group capability to your main application target. Be sure to create and check the checkmark for the App Group in the interface.
  8. Add the Keychain Sharing capability to your main application target. Be sure to add a Keychain Group value to the list.
  9. (Optional) Turn on location updates if you want to use locations or beacons with your app:
  • Go to the Capabilities tab for your target > Background Modes section.
  • Select Location updates. For more information, see Device Location Awareness (DLA).

To complete the integration choose one of the following types of integrations:

The iOS SDK is compatible with the Swift programming language. Any version of the SDK before v3.6.10 does not work with Swift Application Delegates. You can use a workaround by using an Objective-C delegate class. Usage of the SDK from Swift is demonstrated in the Swift sample project starting with V3.6.10.

  1. The automatic integration method requires a main.swift file to be created in the project. It should contain the following:
    
    
    import UIKit import AcousticMobilePush let argv = UnsafeMutableRawPointer(CommandLine.unsafeArgv).bindMemory(to: UnsafeMutablePointer<Int8>.self, capacity: Int(CommandLine.argc)) let _ = UIApplicationMain(CommandLine.argc, CommandLine.unsafeArgv, nil, NSStringFromClass(MCEAppDelegate.self) )
  2. In order for Swift to use the classes in the SDK, you must import the framework at the top of the Swift files that use it. For more information, see Apple Developer documentation.
    
    
    import AcousticMobilePush

    📘

    Note:

    When you use Swift, prefix the package name to the appDelegateClass in the MCEconfig file.

    
    
    { "appDelegateClass": "Sample.AppDelegate" ... // Rest of MceConfig.json file }
  3. Add the following import directive to the top of the AppDelegate.
    
    
    import UserNotifications
  4. Add didFinishLaunchingWithOptions to the application method in your AppDelegate class. This code sets the notification type to badge, sound, and alert. You can remove the unwanted notification types from each OS support level declaration.
    
    
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { 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.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) }) return true }
  1. Replace the AppDelegate class name specification in the main.m file with MCEAppDelegate. The MCEAppDelegate is a proxy delegate. The MCEAppDelegate forwards the calls to the delegate defined in the configuration.

    📘

    Note:

    If additional initializations are done, then you must return the result with MCEAppDelegate. The results of the of UIApplicationMain returned from main must include the MCEAppDelegate.

  2. Replace the contents of main.m with the following:
    
    
    @import UIKit; int main(int argc, char * argv[]) { @autoreleasepool { return UIApplicationMain(argc, argv, nil, @"MCEAppDelegate"); } }
  3. Add the following import directive to the top of the AppDelegate.
    
    
    @import UserNotifications;
  4. Add didFinishLaunchingWithOptions to the application method in your AppDelegate class. This code sets the notification type to badge, sound, and alert. You can remove the unwanted notification types from each OS support level declaration.
    
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [application registerForRemoteNotifications]; NSUInteger options = 0; if(@available(iOS 12.0, *)) { options = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge|UNAuthorizationOptionCarPlay|UNAuthorizationOptionProvidesAppNotificationSettings; } else { options = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge|UNAuthorizationOptionCarPlay; } UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions: options completionHandler:^(BOOL granted, NSError * _Nullable error) { // This isn't required, it's here to demonstrate how to register static category actions [center setNotificationCategories: [self applicationCategories]]; }]; return TRUE; }
  1. Remove the AppDelegateClass section in the MceConfig.json file.
  2. Add -ObjC to the Other Linker Flags build option in Build Settings.
  3. Integrate the following code into your app delegate file:
    
    
    import UIKit import AcousticMobilePush class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? override func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool { // If using the MceConfig.json file: MCESdk.shared.handleApplicationLaunch() // If providing the config via a NSDictionary // MCESdk.shared.handleApplicationLaunch(withConfig:Config.mobilePushConfig) // MCENotificationDelegate provides SDK integration for the UNUserNotificationCenterDelegate methods introduced in iOS 10. UNUserNotificationCenter.current().delegate = MCENotificationDelegate.shared; application.registerForRemoteNotifications() let center = UNUserNotificationCenter.current() center.requestAuthorization(options: [.alert, .sound, .carPlay, .badge], completionHandler: { (granted, error) in print("Notifiations response (granted) (error)") }) return true } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("didFailToRegisterForRemoteNotificationsWithError \(error.localizedDescription)") MCESdk.shared.deviceTokenRegistartionFailed() } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { print("DeviceToken: \( MCEApiUtil.deviceToken(deviceToken) ?? "" )") MCESdk.shared.registerDeviceToken(deviceToken) } }

For more information, see Apple Developer documentation. If you are creating the bridging header for the first time, then complete the following step:

  1. Go to Build Settings > Swift Compiler > Code Generation > Objective-C Bridging Header.
  2. Then, specify the bridging header filename.

  1. Select the target in the project editor.
  2. In the Linked Frameworks and Libraries section, add the following frameworks and dependencies:
    • libz.tbd
    • CoreLocation.framework
    • CoreTelephony.framework
      If these frameworks already exist in the section, you can skip adding them.
  3. Add -ObjC to the Other Linker Flags build options in the Build Settings tab.
  4. Integrate the following code into your app delegate file:
    
    
    #import <AcousticMobilePush/AcousticMobilePush.h> -(void) applicationDidFinishLaunching: (UIApplication *)application { [[MCESdk sharedInstance] handleApplicationLaunch]; [application registerForRemoteNotifications]; NSUInteger options = 0; if(@available(iOS 12.0,*)) { options = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge|UNAuthorizationOptionCarPlay|UNAuthorizationOptionProvidesAppNotificationSettings; } else { options = UNAuthorizationOptionAlert|UNAuthorizationOptionSound|UNAuthorizationOptionBadge|UNAuthorizationOptionCarPlay; } UNUserNotificationCenter * center = [UNUserNotificationCenter currentNotificationCenter]; [center requestAuthorizationWithOptions: options completionHandler: ^(BOOL granted, NSError * _Nullable error) { // This isn't required, it's here to demonstrate how to register static category actions // [center setNotificationCategories: [self applicationCategories]]; }]; } -(void) application: (UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken: (NSData *)deviceToken { [[MCESdk sharedInstance] registerDeviceToken:deviceToken]; } -(void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { [[MCESdk sharedInstance]deviceTokenRegistartionFailed]; }

Update the SDK configuration

  1. Open the MceConfig.json file.
  2. Swift requires your class to be in a namespace. For example, in the Swift sample app, update the appDelegateClass value to SwiftSample.AppDelegate.
  3. Update the dev and prod entries in the appKey section to match the App Keys created in the web portal.
  • The dev entry is used when you run the app from Xcode with a development provisioning profile. The prod entry is used when you run the app with an App Store, Enterprise, or AdHoc provisioning profile.
  • If you do not have a production App Key, use apXXXXXXXX for the prod entry.
  1. Update the baseUrl entry to match the server for your App Key. The baseURL was provided when your account was provisioned for mobile app messaging.
  2. If you are not using Geofences or iBeacons, you can remove the location entry and all its children.
  3. If you are using iBeacons, update the UUID in the iBeacon section of the location entry. The UUID should match the UUID for your iBeacons.

For more information, see Configuration (MceConfig.json).

Add the Notification Service Framework to your app

This framework should be added to your project if you have requirements for:

  • dynamic action categories
  • media attachments
  • other mutable-content support

For more information, see Add the iOS Notification Service Framework to your project.

Test your iOS applications

Apple offers development and distribution profiles for testing and releasing iOS applications. These profiles relate to the application type set up in Mobile Push Notification. Applications built with the development profile are assigned to the development application type. Applications built with the distribution profile are assigned to the production application type.

There are two subclasses of Apple distribution profiles: Ad hoc and App Store. Before you submit your app to the App Store, you must build a version of your app with an ad hoc distribution profile. You can associate your production application with your test devices. You can test Mobile Push Notification and Apple production push facilities.

  1. Go to the Apple iOS provisioning portal, click Devices, and add your test device IDs. You can get your device ID through the Xcode organizer or iTunes. You can find the instructions at Apple Developer documentation.
  2. Click Provisioning > Distribution > New Profile.
  3. Select Distribution Method: Ad hoc.
  4. Select the appropriate app ID associated with the production push service.
  5. Select your test devices and Click Submit.

📘

Note:

Your ad hoc build does not work on devices that are not set up here.

  1. Download your new ad hoc distribution profile to your computer. Then, install it in Xcode by double-clicking it.
  2. Go back to your app in Xcode and go to Project Build Settings.
  3. Under Code Signing > Release, select your new distribution profile.
  4. Select your profile in Target Build Settings as well.
  5. Delete the development version of your app from your device. If it is not deleted, the device may not recognize the production version, and you will not receive a push.
  6. Verify your app is set up correctly on the Acoustic Mobile Push Notification page. The Application Key Type must be production.
  7. The .p12 file that you uploaded must be the production-version of the certificate.
  8. Connect your device to your computer, build the app on your phone, and watch the Xcode console for the string. Attempt to register after your app fires up.
  9. Apple push services, Mobile Push Notification registration success messages, and tokens are shown.

📘

Note:

If the token is the same as your development build, then the Xcode provisioning profile is mismatched.

  1. Connect your iOS device to your computer and build it. Your app and ad hoc provisioning profile are loaded onto your device. You can now begin testing.

  2. Send your app to other test devices.

  • You can connect other test devices to your computer and build the app for them. You must associate the test device ID to the Adhoc profile in the Apple provisioning portal.
  • You can also email the compiled .app and the provisioning profile to your testers. They can drag/drop/sync in iTunes.
  • You can also use the Over the Air method.

Add your app to the app store

  1. After you successfully test your app, edit MceConfig.json and set xLogging to false.
  2. Go back to Apple iOS Provisioning Portal > Provisioning.
  3. Create an app store distribution profile.

📘

Note:

Your app may not receive the appropriate entitlements when added to the app store. For more information, see dirtied provisioning profiles.

  1. Download the new Distribution Profile.
  2. Associate the profile with your Project, and Target Build Settings for Release.
  3. Open the Distribution Profile in a text editor and verify the production values. It must contain the following key/value: aps-environment production.
  4. Build the app.
  5. Go to iTunes Connect and follow the instructions to submit your app for approval. For more information, see iTunes Connect.

📘

Note:

If you use location-based services within your app, you must disclose how you use this data to Apple. For example, “My app can, at the user’s option, use location data to present relevant and timely content.”

Test sending simple push notifications

Using the API, Swagger, or the Campaign UI to send a simple push notification and verify it arrives on your test device.

Send production push notifications

Marketers can now use Acoustic Campaign to create, schedule, and send mobile app messages. For more information, see Create and send a mobile message.