Last modified June 3, 2016 by Shelly Wolfe

iOS

Swrve is a single integrated platform that delivers everything you need to drive mobile engagement and create valuable customer relationships on mobile.
The Swrve native iOS SDK enables your app to use all of these features. This guide contains all the information you need to integrate the SDK into your app.
With the release of Swrve’s iOS SDK version 5.0, we have made major changes to the SDK methods and APIs. The code examples in this guide refer exclusively to version 5.0+.

Requirements

  • The Swrve iOS SDK supports iOS 8 and later but is able to handle iOS 6 and 7 with a dummy SDK.
  • Ensure you have the latest version of Xcode.
  • If you’re developing your app in Swift, we recommend upgrading to the latest SDK version to prevent compatibility issues with iOS 8. For more information, see Integrating the iOS SDK Using Swift.
  • The App ID and API Key for your app. This information is available in Swrve on the Integration Settings screen (on the Setup menu, click Integration Settings).

Frameworks

The Swrve SDK references the following frameworks.

Required:

  • CFNetwork.framework
  • StoreKit.framework
  • Security.framework
  • QuartzCore.framework
  • CoreTelephony.framework
  • UIKit.framework
  • MessageUI.framework
  • CoreLocation.framework
  • AVFoundation.framework
  • CoreText.framework
  • UserNotificationsUI.framework
  • UserNotifications.framework

If you want to exclude the push notification feature, you can remove the following frameworks by adding associated preprocessor macros (For more information, see How Do I Exclude Optional iOS Frameworks?):

  • UserNotificationsUI.framework
  • UserNotifications.framework

Optional:

  • AddressBook.framework
  • AssetsLibrary.framework
  • Photos.framework
  • Contacts.framework
If you want to include the above optional frameworks in your integration, you must add associated preprocessor macros for each framework. For more information, see How Do I Exclude Optional iOS Frameworks?

Automatic Reference Counting

If your Xcode project does not use Automatic Reference Counting (ARC), and you’re manually installing the SDK (that is, not using CocoaPods), you must enable ARC for each file in the Swrve SDK.


Installing the SDK

CocoaPods

Step 1: In your project’s Podfile, add the following dependency:

Step 2: Run the following command to install the new dependency:

Carthage

Step 1: In your project’s Cartfile, add the following dependency:

Step 2: Run the following command to install the new dependency:

Manual Installation

Step 1: Download the SDK from the GitHub public repository or download a .zip file of the latest iOS SDK.

Step 2: Unzip the iOS SDK, copy the contents of the SDK folder into your Xcode project and link against the frameworks listed above.

Installing the SDK in a Swift Project

If you’re manually installing the SDK in a Swift project, you must build a project bridging-header.h file that includes the following line:

Installation Demo

This video shows you how to install the SDK, set up a QA user and run a simple campaign.

For code examples from the most recent version of the Swrve iOS SDK, please refer to the sections below.

Basic Integration

After you have installed the SDK, complete the following steps for a basic integration. Replace <app_id> and <api_key> with your app ID and API key.

Depending on your data requirements, Swrve stores all customer data and content in either our US or EU data centers. If you require EU data storage, include the EU stack information in the example below to configure the SDK to point to Swrve’s EU-based URL endpoints. If you have any questions or need assistance configuring the SDK for EU data storage, please contact support@swrve.com.

Step 1: In your App Delegate source file (usually named AppDelegate.m), add the following code snippet to the didFinishLaunchingWithOptions method.

Objective-C

Swift

The DEBUG macro should be present in the Preprocessor Macros by default. If not present, please add DEBUG=1 to your debug configuration under Preprocessing > Preprocessor Macros > Debug.

Step 2 (Optional): With iOS 9, by default all communications between the app and its backend or the web should use HTTPS. (See the App Transport Security section in Apple’s What’s New in iOS 9.0 guide.) Swrve’s API URL endpoints are now all HTTPS-capable and the API calls default to HTTPS. However, if you’re planning to use YouTube videos as content in your Conversations, add an Application Transport Security exception to your <App>-Info.plist.

This is needed, as even HTTPS YouTube links use non-secure endpoints that keep changing over time.

Step 3 (Optional): If you are planning to use or ask for location tracking permission, add the following keys to your <App>-Info.plist if not already there (edit the Value message to whatever text you want):

  • NSLocationAlwaysUsageDescription – Value: Your location is used to instantly inform you when you are near a location that is of interest to you.
  • NSLocationWhenInUseUsageDescription – Value: Your location is used to instantly inform you when you are near a location that is of interest to you while the app is in use.
  • NSLocationAlwaysAndWhenInUseUsageDescription – Value: Your location is used to instantly inform you when you are near a location that is of interest to you.

The project is now ready to compile and run in the iOS simulator.

Basic integration of the Swrve SDK enables you to track important metrics and run in-app messages and Conversations campaigns. To make use of additional Swrve features, such as push notifications and advanced metrics tracking, complete the following sections as required.

In-App Messages and Conversations

Swrve’s in-app messages and Conversations campaigns are available as soon as you complete the basic integration described above. These features enable you to send personalized messages to your app users while they’re using your app. For more information, see Intro to In-App Messages and Intro to Conversations.

To test in-app messages or Conversations in your app, you need to first create the campaign in Swrve. For more information, see Creating In-App Messages and Creating Conversations.

If you want to display an in-app message or Conversation as soon as your view is ready, you must trigger the display event when the view controller is in the viewDidAppear state and not in viewDidLoad state.

In-App Message and Conversation Deeplinks

When creating in-app messages and Conversations in Swrve, you can configure message buttons to direct users to perform a custom action when clicked. For example, you might configure a button to direct the app user straight to the app store to provide a rating.

Swrve’s default deeplink behavior for in-app messages and conversations is to treat deeplinks as URLs, so you can use your existing custom URL scheme. If you have not already registered a custom URL scheme, you’ll need to do this before using deeplinks from in-app messages and conversations.

Once the custom URL scheme is set, your app can receive and direct users from outside of the app.

In-App Message Custom Actions

For conversations, deeplinks strings are always handled as URLs. For in-app messages, it is also possible to override this behavior of treating custom actions as URL deeplinks and integrate custom actions to direct users to a sale, website or other target when they click an in-app message. Use the following callback:

Objective-C

Swift

For example, to send Swrve events using custom actions, add a customButtonCallback like this:

Objective-C

Swift

Overriding In-App Message Display

Swrve’s iOS SDK displays in-app messages automatically. The messages are implemented as objects of the type UIWindow that are displayed on top of your app’s top-most view. You may need to customize this approach in certain circumstances; for example, if you require full control over the animated segue or fine-grained control over the view hierarchy. If you require this level of control in your app, contact your Customer Success Manager at support@swrve.com and inform them about your particular needs.

To override the default display mechanism, your app must supply a delegate object that implements the SwrveMessageDelegate protocol. You must then assign your delegate to SwrveMessageController.showMessageDelegate. For more information, see the inline documentation in the SwrveMessageController.h header file.


Push Notifications

Swrve’s push notification campaigns enable you to send personalized messages to your app users while they’re outside of your app or send silent background app updates. For more information, see Intro to Push Notifications.

This section covers how to integrate basic Swrve push notifications. To include rich media content and custom buttons in your push notifications, you must also complete the steps outlined in the Advanced Push Notifications section.

Push notifications are disabled by default. To enable them, set SwrveConfig.pushEnabled to YES. In addition, you must tell the Swrve SDK when your app receives a push notification (this is required for push notification reporting in the Swrve service).

If you are using iOS 8+ Interactive Notifications, you must also declare the custom action categories to the Swrve SDK (see example below). However, for iOS 10+, you must use the notification categories in UNNotificationCategory (for more information, see Processing Notification Responses, Step 4 under Advanced Push Notifications).

Your app must also handle the following two situations:

  • The app is launched from a push notification.
  • The app receives the push notification while running.

Objective-C

Swift

The remainder of the initialization process depends on how you want to request permission from the user to accept push notifications.

Timing the Device Token (Push Permission) Request

When a user first installs a push-enabled app, the app requests the latest device token for push notifications. This triggers a permission request to the user to accept push notifications from the app. Swrve has built-in functionality to manage the timing of this request. There are two options:

  • Start of the first session (default configuration) – This is the simplest option and requires no additional code changes.
  • When one of a list of events is triggered – To request permission when certain events are triggered, add the event names to SwrveConfig.PushNotificationEvents when you initialize the SDK. For example:

Objective-C

Swift

If a user never triggers these events, they will never be available for push notifications, so select events that are most likely to be triggered by all but the most transient of users.

For more information about uploading device tokens, see How Do I Upload Push Device Tokens?

Apple only asks for permission to receive push notifications once per app, under normal circumstances. As a result, when you want to test your push notification integration on a QA device, you must reset the iOS push permissions to test the different timing configurations for push permissions outlined above. For more information, see How Do I Reset iOS Permissions?

Configuring Silent Notifications

To enable silent push notifications in your app, complete the following:

The purpose of a silent notification is to deliver data to your app in the background, such as a content update. You should never call the SDK from a silent notification.

Step 1: Modify your .plist, or on the Capabilities tab, under Background Modes, enable the Remote notifications background mode.

Silent notifications iOS

Step 2: Call the Swrve SDK from the following method in your AppDelegate.m:

Objective-C

Swift

Note: When a silent notification is delivered to the user’s device, iOS wakes up your app in the background and gives it up to 30 seconds to run. Ensure you initiate any download operations needed to fetch new data within that 30 second window.

Step 3: Add code to your app to remove the badge number notification, for example, in the applicationWillEnterForeground callback:

Processing Custom Payloads

If you want to capture any custom key/value pairs passed with the push notification, capture the notification data in your application’s didFinishLaunchingWithOptions and use the delegate methods provided by SwrvePushResponseDelegate.

Note: You must define the delegate class before you initialize Swrve.

Objective-C

Swift

The method above enables you to specify any launch parameters that you want to capture and take action on. For more information, see Configuring the Launch Screen.

Disabling Push Notification Method Swizzling

In order to reduce the number of code changes required to implement push notifications using the Swrve SDK, by default method swizzling is used around the iOS push notification methods.

In some cases, especially where custom handling of push notification methods is required, it is necessary to disable the Swrve SDKs push notification method swizzling. Use the following code if you want to disable method swizzling:

Objective-C

Swift

Creating and Uploading Your iOS Certificate

To enable your app to send push notifications to iOS devices, you require a push certificate. A push certificate authorizes an app to receive push notifications and authorizes a service to send push notifications to an app. For more information, see How Do I Manage iOS Push Certificates?

Provisioning Your App

Each time your app is published for distribution, you must provision it against the push certificate that has been created for the app.


Advanced Push Notifications

As of iOS SDK version 4.11, Swrve enables you to include rich media options in your push notification content. To display rich push notifications in your app, iOS uses a notification service app extension. This section describes how to add a service extension to your app. It also includes how to process notification responses and handle tracking influenced users of rich push notifications, if required.

For examples of how to integrate rich push notifications in the Swrve iOS SDK, see the Swrve iOS SDK Samples folder on GitHub.

Creating a Notification Service Extension for Swrve Rich Push

To create a notification service app extension for Swrve rich push notifications:

Step 1: In Xcode, add a service extension to your project:

  1. Select New > Target to add a new target to your project.
  2. In the iOS > Application Extension section, select the Notification Service Extension target and then click Next.
  3. Specify the name and other details for your app extension and then click Finish.
    Note: When naming the service extension, it’s important that the start of the Bundle identifier for the service extension is the same the main app’s. For example:
    Main App: swrve.MyAwesomeApp
    Service extension: swrve.MyAwesomeApp.MyAwesomeServiceExtension
  4. When prompted, click Activate to activate the extension.

Step 2: Since service extensions were only introduced in iOS 10, change the Deployment Target of the service extension to 10.0 to maximize compatibility with iOS 10+ versions of the app. (The Deployment Target of the app can be lower than iOS 10.)

Step 3: In CocoaPods, add a new target block with the same name as your service extension and only include the latest SwrveSDKCommon pod (that is, from the same version of the SDK that your main app uses). For example:

Do not include the SwrveSDK pod. It is not required for a service extension and, as certain features in the SwrveSDK pod are not permitted in a service extension, will cause compilation errors.

Step 4: For both the service extension and your main app, on the Capabilities tab, ensure Push Notifications are enabled:

Xcode push notifications enabled

Step 5: Run a pod install.

Step 6: Import Swrve Push and add the following to the service extension NotificationService class:

Objective C

Swift

Step 7: For debugging, set the Executable of your service extension target to your main app.

On iOS 10, there is an intermittent issue with notification service extensions where, in some debugging instances, the rich media attachment is not displayed. This is a common issue that has been raised with Apple, but should not affect the production version.

If you are managing provisioning profiles for your app, you must create one for your service extension as well.

Step 8: Start your application and ensure that it’s registered for push notifications.

Step 9: To verify the service extension has been set up correctly, send a rich push notification to your QA device.

If you experience any issues, in your main app check that the service extension is added to the Embedded Binaries (this should be done automatically by Xcode).

Processing Notification Responses

With the addition of custom buttons to the push campaign workflow, if desired, you can also manage the expected response of notifications for the following scenarios:

  • How the notification is displayed when the app is running in the foreground.
  • How the user engages with the notification.

If you don’t need to do anything with the push notification response, no other steps are needed. Swrve automatically tracks and reports on engagement in the push campaign report. If you want to add any additional work, complete the following:

Step 1: Set the class in which you initialize Swrve to be a SwrvePushResponseDelegate and add the following to the SwrveConfig:

Objective C

Swift

This should be done before Swrve is initialized. Otherwise, there’s a chance the delegate will not be attached to our push processing at the time a user engages with a notification or button.

Step 2: Add the SwrvePushResponseDelegate methods to the class you’ve set as the pushResponseDelegate:

  • didReceiveNotificationResponse  – used for processing when the user interacts with the notification. Once this is fired, we’ve already processed the userInfo and events so it’s up to you if you want to include any additional actions. Ensure you call the completionHandler() at the end.

    Objective-C



    Swift



  • willPresentNotification  – used when the app is running in the foreground. Inside the function, you can choose to display an alternative UI or even the push itself if you pass any of the UNNotificationPresentationOptions values into the completionHandler as shown below.

    Objective-C



    Swift



Step 3: If you are configuring your own notification categories for given instances, we have provided two other SwrveConfig properties to fill before initializing Swrve. These are notificationCategories for Apple’s iOS 10 Push Notification Framework (UNNotificationCategory) and pushCategories for backwards compatibility (UIUserNotificationCategory). We recommend adding them to SwrveConfig as follows:

Objective C

Swift

Step 4: When receiving push notification responses from iOS versions prior to iOS 10 and the new framework, implement the following function to facilitate tracking in the Swrve SDK:

Objective C

Swift

Tracking Influenced Users

As of Swrve iOS SDK version 4.10 and the addition of silent notifications, Swrve automatically tracks influenced metrics (that is, if a user opens your app within a certain window after receiving the push notification). Prior to iOS SDK version 4.11, you could only add a badge to the application view via a silent notification. It is now possible to track influenced from a rich push, however to do so, the application needs to share stored information with the service extension. An app group enables the service extension to save the influenced data to shared container that the main app can access on startup.

To add an app group:

Step 1: In the Apple Developer portal, create a new App Group. Enter the description and name as group.BundleID.

Step 2: On the portal, go to your app ID for your main app, add the App Group capability and select your new App Group in the checkbox provided.

When you check the Application Services on the portal, App Groups should be enabled.

app groups enabled

Step 3: Repeat the above step for the app extension.

Step 4: If your provisioning profiles are not handled by Xcode, you will need to regenerate them as adding an app groups will make them invalid. For example:

regenerate provisioning profile

Select the profile, click Edit and then click Generate. It is not necessary to make a new provisioning profile, as the status will change to Valid after you click Generate.

Step 5: In Xcode, for both the app and app extension, go to the Capabilities tab, enable App Groups, and select your App Group.

A notification window should appear with the message, “iOS Test App Service Extension Development profile is out of date. Download an updated version from the developer website.” Click Update.

Select the App Group for both targets.

app groups enabled

Step 6: In your SwrveConfig, add the same identifier for your app group to the appGroupIdentifier property:

Step 7: In the service extension, where you call the function handleNotificationContent, include the same appGroupIdentifier.

Step 8: Compile and run the app.

Send a rich push notification to your QA device, do not interact with it but open the app directly and you should see influenced events coming in to your reporting.


Sending Events

The Swrve SDK automatically sends certain events and also enables you to track user behavior by sending custom events.(For a list of default Swrve events, see About Audience Filters, Events.) In turn, you can use app-generated events to trigger in-app messages, while both app- and server-generated events help you define segments and perform in-depth analysis.

Custom Events

To send a custom event, include the below example in a method where you want to send an event to Swrve.

Objective-C

Swift

Requirements for sending custom events:

  • Do not send the same named event with different case. For example, if you send tutorial.start, then ensure you never send Tutorial.Start.
  • Use a period (.) in your event names to organize their layout in the Swrve dashboard. Each ‘.’ creates a new branch in the Event name column of the Events report, and groups your events so they are easy to locate.
  • Do not send more than 1000 unique named events.
    • Do not add unique identifiers to event names. For example, Tutorial.Start.ServerID-ABDCEFG
    • Do not add timestamps to event names. For example, Tutorial.Start.1454458885
  • Do not use the swrve.* or Swrve.* namespace for your own events. This is reserved for Swrve use only. Custom event names beginning with Swrve. are restricted and cannot be sent.

Event Payloads

You can add and send an event payload with every event. This allows for more detailed reporting around events and funnels.

Notes on associated payloads:

  • The associated payload should be a dictionary of key/value pairs; it is restricted to string and integer keys and values.
  • There is a maximum cardinality of 500 key-value pairs for this payload per event. This parameter is optional, but only the first 500 payloads are displayed in the dashboard. The data is still available in raw event logs.
  • It is not currently possible to use payloads as triggers on push notifications or for audience filters in the dashboard. Use events for these purposes.

Objective-C

Swift

For example, if you want to track when a user starts the tutorial experience, it might make sense to send an event named tutorial.start and add a payload time that captures how much time it took the user to complete the tutorial.

Objective-C

Swift

Custom User Properties

The Swrve SDK sends certain user properties by default and also enables you to assign custom properties to update the user’s status. (For a full list of the default user properties, see Assigning User Properties.)

For example, you could create a custom user property called premium, and then target non-premium users and premium users in your campaigns.

When configuring custom properties for iOS, you can use a variety of data types (integers, boolean, strings) that the SDK then converts to an integer (for number-based values) or string (in the case of boolean, “true/false”) before sending the data to Swrve. When creating segments or campaign audiences, depending on which data type the property is converted to, you must then select the correct operator (equals for numbers, is for strings) for the property to be properly returned.

Example of group of user properties

Objective-C

Swift

Example of single date-typed user property

Use the NSDate object to send a DateTime user property; for example, the current date at the time of a user purchase:

Objective-C

Swift

Virtual Economy Events

To ensure virtual currency events are not ignored by the server, make sure the currency name configured in your app matches exactly the Currency Name you enter in the App Currencies section on the App Settings screen (including case-sensitive). If there is any difference, or if you haven’t added the currency in Swrve, the server will ignore the event and return an error event called Swrve.error.invalid_currency. Additionally, the ignored events are not included in your KPI reports. For more information, see Add Your App.

If your app has a virtual economy, send the purchase event when users purchase in-app items with virtual currency.

Objective-C

Swift

Send the currency given event when you give users virtual currency. Examples include initial currency balances, retention bonuses and level-complete rewards.

Objective-C

Swift

In-App Purchase Events and Validation

If your app has in-app purchases (IAPs), send the IAP event when a user purchases something with real money.

Notify Swrve when an in-app purchase occurs as follows:

Objective-C

Swift

Enabling IAP Receipt Validation

Swrve automatically validates iOS in-app purchases and ignores any events that are considered fraudulent as per Apple guidelines.

To enable validation of IAP receipts against your app:

Step 1: On the Setup menu, click Integration Settings.

Step 2: Under IAP Validation, in the iTunes App Bundle Identifier section, enter your Apple Bundle Id.

Step 3: Click Save.

Although Swrve can validate IAP receipts without this identifier, providing it enables Swrve to verify a receipt against the app itself for greater precision during validation. Swrve checks that the bundle ID included in an in-app purchase receipt corresponds to your bundle ID before calculating your revenue KPIs. This ensures that your revenue figures are as accurate as possible (ignoring pirates and cheaters).

Generally, you enter the Apple bundle ID when configuring the Integration Settings screen as part of the Swrve onboarding process. You can edit the settings on this screen at any time.

To access your bundle ID, access the information property list file (<App>-Info.plist) in your Xcode project.

Verifying IAP Receipt Validation

Use the following events to monitor the success of IAP receipt validation:

  • swrve.valid_iap – fired if receipt verification is successful and the receipt is valid.
  • swrve.invalid_iap – fired if receipt verification is successful and the receipt is invalid.

Unvalidated IAP

If you want to build revenue reports for your app but don’t have or want the receipt to be validated by our servers, use the function below. This might be required for any purchases in the app that are not made via Apple—this revenue should be validated before this function is called, as any revenue sent by this event is automatically counted in the Swrve dashboard.

Objective-C

Swift


Resource A/B Testing

Integrating Swrve’s resource A/B testing functionality enables you to use Swrve to test how users respond to changes to the native app content. For more information about resource A/B testing, see Intro to Resource A/B Testing.

To get the latest version of a resource from Swrve using the Resource Manager, use the following:

Objective-C

Swift

If you want to be notified whenever resources change, you can add a callback function as follows:

Objective-C

Swift


Testing Your Integration

After you’ve completed the above, the next step is to test the integration. For more information, see Testing Your Integration.


Upgrade Instructions

If you’re moving from an earlier version of the iOS SDK to the current version, see the iOS SDK Upgrade Guide for upgrade instructions.


SDK Samples

For sample integrations of the Swrve iOS SDK, see the Swrve iOS SDK samples on GitHub.