iOS SDK Integration guide

Document created by Akhil Jayaprakash Employee on Jan 27, 2016Last modified by Brian Salomon on Jun 13, 2016
Version 10Show Document
  • View in full screen mode

Summary

This document details the process of integrating VOC SDK with your iOS application to accelerate Web traffic.

Introduction

The SDK internally pre-positions Web content based on user preferences and policies set up between the client and server. APIs (networking libraries) are provided that take care of acceleration and statistics collection.

The SDK also provides an API for developers to access real-time network conditions such as congestion state. This information can be used to augment the user experience by taking necessary actions based on network state.

APIs are also available for logging user events.  These can be used to associate traffic originated from the app with events such as tapping a button.

Getting Started

 

Step 1: Click here to download the iOS SDK

 

Step 2: proceed with the document

 

iOS provides several ways to request network resources via HTTP and HTTPS.  Direct URL requests can be made through the Foundation classes NSURLConnection and NSURLSession.  Entire Webpages can be retrieved and displayed through the view controllers UIWebView, WKWebView, and SFSafariViewController.  Both direct download approaches are accelerated by the VOC SDK.  UIWebView is also accelerated.

 

 

Request Type

Requires Extra Setup?

NSURLConnection

Direct

NO

NSURLSession

Direct

YES for custom sessions

UIWebView

Web view

NO

Table 1 - URL Request Types

 

NSURLConnection and UIWebView are automatically accelerated once the SDK is installed.  NSURLSessions using a custom configuration require a configuration call.  Each approach is covered in the API Reference section.

The VOC SDK library also collects network related statistics (such as HTTP time to first byte, request size, response size, duration, etc.) while serving content. These stats are sent periodically to the VOC server for later access via the Web portal.

Installing the iOS SDK

  1. Download the VOC SDK and unzip it in a folder under your project, e.g. ~/myproject/voc_sdk.
  2. Locate the VocSdk.framework under ~/myproject/voc_sdk/iphoneos/ and copy it into your project folder, e.g. ~/myproject/VocSdk.framework.  This makes the framework available before the first build so you can add it to your project.  On each build afterward it will be copied here by the copy_vocsdk build phase script.
  3. Add the framework to your Xcode project.
    1. Open your project in Xcode.
    2. Open the File menu.
    3. Click Add Files to <project>.
    4. Choose ~/myproject/VocSdk.framework
  4. Link the SDK to your project.
    1. Open project settings by clicking the project name in the Project navigator.
    2. Click the General tab.
    3. Under Embedded Binaries, click + and choose VocSdk.framework.
    4. Click Add.
  5. The right framework for your platform -- simulator or device -- must be copied into place before building your app. This requires a build phase to be added to your project settings.
    1. In your Project Settings, click on Build Phases.
    2. Click the “+” to add a new build phase, and choose “New Run Script Phase.”
    3. Drag this build phase to position it after Target Dependencies.
    4. Optionally single-click its name and rename it to copy_vocsdk.
    5. Click the arrow to expand the copy_vocsdk row.
    6. Leave the default shell setting of /bin/sh.
    7. In the script area, add the following text. The "copy_vocsdk.sh" path is relative to your .xcodeproj file and may need modification depending on where you unzipped it.

 

./voc_sdk/copy_vocsdk.sh "${PROJECT_DIR}/voc_sdk"

 

The second parameter, "${PROJECT_DIR}/voc_sdk", is the location of the /iphoneos and /iphonesimulator folders from the distribution archive.

 

In this example, the folder structure is as follows:

 

                    /myproject/myproject.xcodeproj

                    /myproject/voc_sdk/copy_vocsdk.sh

                    /myproject/voc_sdk/iphoneos/

                    /myproject/voc_sdk/iphonesimulator/

 

               The script will copy the correct VocSdk.framework to the /myproject/ folder at the start of every build.


The final build phase should look like this:

Integrating with your iOS Application

Including the SDK

The SDK is made available to your code through the AkaWebAccelerator protocol.  Import the VocSdk header wherever the SDK is required.  SDK setup typically happens in the app delegate, so the following is added to AppDelegate.h to declare the main service.

#import <VocSdk/VocSdk.h>

@property (strong, nonatomic) id<AkaWebAccelerator> akaService;

Initialization

SDK functionality is activated by the VocServiceFactory call createAkaWebAccelerationWithDelegate:delegateQueue:options:error:.  Initialization and registration should take place early in the app lifecycle to ensure that acceleration is available for the first network request. The recommended place for this is in AppDelegate’s application:didFinishLaunchingWithOptions:.  The create call inputs a configuration dictionary and a reference to the SDK delegate discussed in the SDK Delegate section below.  The SDK delegate is the class you designate to respond to SDK activity.

 

The example below is inserted into AppDelegate.m.  It initializes the SDK and tells it that AppDelegate will be the delegate to handle any SDK messages.

 

- (BOOL)application: (UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
    NSError *error = nil;
    self.akaService = [VocServiceFactory createAkaWebAcceleratorWithDelegate:self
                             delegateQueue:[NSOperationQueue mainQueue]
                             options:nil
                             error:&error];

    if (!self.akaService) {
        // error handling - could not start service
        return NO;
    }

    // app initialized
    return YES;
}

 

 

Registration

Registration is a one-time event that activates the VOC service with a particular license key.  This key is linked to prepositioned content, generation of usage statistics, and other SDK capabilities. It is required for most SDK features so registration should occur early within the application.

 

Developers may also choose to set the customer code string, akaService.config.customerCode.  If present, this code will be included in all request headers sent from the SDK.

 

The first registration attempt is made automatically by the initialization call in app delegate, described in the Initialization section above.  If a user had been registered during a previous app session, initialization will automatically register that user again. Checking the VocService state immediately after initialization indicates whether a user is already registered.

 

If no user was registered during initialization then the VocService state is VOCServiceStateNotRegistered and registration must be run as follows.  This should occur early in the app lifecycle, such as the app’s first view controller.

[appDelegate.akaService registerWithLicense:sdkLicense
                         sdkUser:sdkUser
                         completion:^(NSError * __nullable error) {
                               if (error) { // handle failed registration };
}];


Registration may include an optional user or group ID. This ID is associated with a particular content set defined on the server portal, such as “daily deals.” It may be any string that does not reveal personal information; good examples are customer IDs or group numbers generated specifically for this purpose. Set the ID to nil to register by license key alone. This will associate the user with the default content set defined on the portal.

 

Please Note: It is strong recommended that PII (Personally Identifiable Information) NOT be used in the user ID directly.

 

The SDK calls the VocServiceDelegate’s didRegister: after a successful registration.  This can be used to transition past a login screen, for example, and into the app.  SDK functions requiring a valid user are now available.

SDK Delegate

The SDK notifies your app of various events throughout its life cycle. Messages are sent asynchronously to an SDK delegate in your code that implements the VocServiceDelegate protocol. All of the delegate methods are optional.

- (void) vocService:(nonnull VocService *)vocService didBecomeNotRegistered:(nonnull NSDictionary *)info;
- (void) vocService:(nonnull VocService *)vocService didFailToRegister:(nonnull NSError *)error;
- (void) vocService:(nonnull VocService *)vocService didRegister:(nonnull NSDictionary *)info;

- (void) vocService:(nonnull VocService *)vocService didInitialize:(nonnull NSDictionary *)info;

- (void) vocService:(nonnull VocService *)vocService itemsDiscovered:(nonnull NSArray *)items;
- (void) vocService:(nonnull VocService *)vocService itemsStartDownloading:(nonnull NSArray *)items;
- (void) vocService:(nonnull VocService *)vocService itemsDownloaded:(nonnull NSArray *)items;
- (void) vocService:(nonnull VocService *)vocService itemsEvicted:(nonnull NSArray *)items;

 

The SDK delegate is passed to the SDK in the initialization call.  Typically, this is the app delegate since its lifetime will span that of the SDK, from registration until shutdown. Define your app delegate as follows to implement the SDK delegate protocol.

@interface AppDelegate : UIResponder <UIApplicationDelegate, VocServiceDelegate>

API Reference

Prepositioned Content

Prepositioned content begins loading onto the device once the user is registered.  This happens automatically while your program runs. Network requests are answered with prepositioned content, and if the content is not prepositioned then it will be fetched from the network. Your app can listen for the AkaService -didInitialize: callback to know when the SDK has begun handling requests. This is a onetime event that happens after creating the service.

NSURLConnection

Requests using NSURLConnection will take advantage of preloaded content without any modifications.  For example, an asynchronous NSURLConnection can be created as before and will see the benefits of the SDK’s acceleration.

NSURL *requestURL = [NSURL URLWithString:@"https://www.akamai.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:requestURL];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
// Followed by the asynchronous response handlers: connection:didReceiveResponse:, connection:didReceiveData:, etc.

Synchronous connections are similarly straightforward.  No changes are required to benefit from the SDK's acceleration.

NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

UIWebView

UIWebView will also use prepositioned content automatically and without modification.

NSURLSession

NSURLSession may use either the shared app session or a custom configuration.  The SDK automatically accelerates the shared session, so a standard NSURLSession is accelerated by default:

NSURLSession *session = [NSURLSession sharedSession];
NSURL *requestURL = [NSURL URLwithString:@"http://www.akamai.com/"];
[[session dataTaskWithURL:requestURL] resume];

Alternatively, an NSURLSession may be created with a custom configuration.  The custom configuration is passed into the SDK for setup. Pass the configuration into the VocServiceFactory call setupSessionConfiguration:.

NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration];
// ... modify sessionConfig as required by the app ...
[VocServiceFactory setupSessionConfiguration:sessionConfig]; // sessionConfig now uses SDK acceleration
NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
NSURL *requestURL = [NSURL URLwithString:@"http://www.akamai.com/"];
[[session dataTaskWithURL:requestURL] resume];

Custom Event Tracking

Custom events are actions triggered by the user such as tapping a button or opening a particular screen.  These are defined by the developer.  The SDK provides an API for logging them to the server and optionally timing them.

 

Custom events are classified as timed or instantaneous. A timed event has associated start and end points.  The two endpoints are paired with matching event names, and the time between endpoints is recorded. In addition to logging durations, timed events are useful for monitoring the network activity between endpoints.  For example, custom event starting and stopping points can be recorded in-line with network activity and then be monitored from the Web portal.

[akaService startEvent:@"Event name"];
// activity
[akaService stopEvent:@"Event name"];

Instantaneous events are recorded in the server logs along with the time they were executed. They are useful for recording a sequence of activities or to form a timeline of events.

// instantaneous event
[akaService logEvent:@"tapped home button"];

Network Aware Experience

Developers may query the SDK for the current network congestion level.  A block is passed to the SDK for a one-time response.  The congestion status reports either no congestion (best connection), medium congestion, or high congestion (slow connection).

[appDelegate().akaService getCongestionStatusWithCompletion:^(VocCongestionStatus congestionStatus, NSError *error) {
    if (error) { return; //handle error }
    switch(congestionStatus) {
        case VocCongestionLevelHigh:
            // Exit download
            break;
        case VocCongestionLevelMedium:
            // Throttle download.
            break;
        case VocCongestionLevelNoCongestion:
            // Download content.
            break;
    }
}];

Appendix - Requirements and Dependencies

Platform

The SDK requires iOS 8 or higher.

Background Execution

VoC SDK downloads content while the application is running. Various factors determine when to start downloading, how much to download, and when to pause downloads. Influencing factors include the state of the mobile network and the congestion state of the provider network.

 

When your app is in the foreground, downloads are happening without any need for changes in your code. However, in order to get best results, the VoC SDK should be able to download when your app is not in the foreground. In order to do that, you need to enable your app for background execution. There are two types of background execution that VoC SDK uses to download content.  Enable these two modes within the Xcode project settings, Capabilities tab, Background Modes section:

  • Remote notifications (remote-notification)
  • Background fetch (fetch)

To enable background fetch in VoC SDK, you need to implement the system method
          UIApplicationDelegate application:performFetchWithCompletionHandler:
and, from there, pass the message to the AkaService by calling
          AkaService application:performFetchWithCompletionHandler:
Here is what that looks like:

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler
{
    if (![self.akaService application:application performFetchWithCompletionHandler:completionHandler]) {
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

 

Remote Notifications

To make VoC SDK remote notifications work you need to 1) enable VoC backend to send push notifications to your app, and 2) make the supporting code changes.

To enable the VoC backend to send push notifications to your app, you need to upload your app push certificate (APNS) to the VoC license management portal. The VoC backend must have a valid APNS certificate for your app at all times otherwise push notifications will not work. If you revoke or renew your certificate, make sure you upload it to the VoC license management portal. Instructions on how to generate an APNS push certificate are available on Apple’s web site at: https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/AddingCapabilities/AddingCapabilities.html#//apple_ref/doc/uid/TP40012582-CH26-SW11

First, the token is handed off to the SDK in the AppDelegate call application:didRegisterForRemoteNotificationsWithDeviceToken:.

- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    [self.akaService setDevicePushToken:deviceToken];
}

 

Also in your application delegate, implement the system method
          UIApplicationDelegate application:didReceiveRemoteNotification:fetchCompletionHandler:
and pass this to the AkaService
          AkaService application:didReceiveRemoteNotification:fetchCompletionHandler:

For example:

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler

{
    if ([self.akaService application:application didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler]) {
        // remote notification was for VoC SDK
        return ;
    }

    // remote notification is not for VoC SDK, handle remote notification
    completionHandler(UIBackgroundFetchResultNoData);
}



2 people found this helpful

Attachments

    Outcomes