Upsight logo Back to top

iOS

Overview

Upsight iOS SDK


Upsight is the most comprehensive analytics and marketing platform for Web and mobile apps. We are building a business engine to help our customers better understand user behavior, decide what it means, and act to impact key goals.

If you have any questions, contact Upsight Support. We also recommend reviewing our Optimization Guides to learn the best practices and get the most out of your Upsight integration.

Upsight's iOS SDK supports iOS 8 and above.

Getting Started

Cocoapods


Upsight can be installed via cocoapods. To do so, simply add pod 'UpsightKit', '~> 4.9' similar to the following in your Podfile:

target 'MyApp' do
  pod 'UpsightKit', '~> 4.9'
end

Then run a pod install inside your terminal, or from CocoaPods.app.

If you install the Upsight SDK in this way, you can skip down to the debugging section.

You can read more about our cocoapod on the UpsightKit page.

Getting Started

Xcode Documentation


The Upsight iOS SDK uses appledoc to generate visually appealing API method documentation in the form of HTML. These docs are fully indexed and browsable through Xcode.

In order to use the appledoc, extract the iOS SDK zip file and run the following commands:

$ ./install_docsets.sh

Note Installing the Upsight documentation will fail if you have not installed any documentation yet. If the installation process fails, navigate to the Downloads section of Xcode settings and download any other documentation modules. Then run the script again.

To see the Upsight Documentation, click Help > Documentation and API Reference. On the left hand side, you will find the UpsightKit Documentation.

Getting Started

Basic Integration


To begin, you will need to download the iOS SDK.

Integrating Upsight's iOS SDK is as simple as 3 easy steps.

  1. From the Upsight SDK folder, drag UpsightKit.framework into your Project’s Framework folder in the Xcode Navigator window. Ensure that UpsightKit.framework was added to the Build Phases section of the target settings. Then add Foundation.framework, CoreTelephony.framework, AdSupport.framework, libxml2.tbd , and MediaPlayer.framework provided by Apple to the Build Phases section. Additionally, if you are using Push Notifications or mediation, add the UserNotifications.framework as Optional. Integration step 1

  2. Navigate to the 'Info' page of the project settings. Under 'Custom iOS Target Properties' create a key called UpsightAppToken with String as a Type and copy your Upsight App Token to the value field. Next create a key called UpsightPublicKey with String as a Type and copy your App Public Key as a string to the value field. These are provided on the Upsight dashboard under Settings > Applications > App Name. Integration step 2

  3. In the Build Settings section of the target, add -ObjC to the Other Linker Flags field. Integration step 3

    Note -ObjC tag is case sensitive.

Getting Started

Debugging


To start with, turn on full debug logging:

  1. Add #import <UpsightKit/UpsightKit.h> at the top of your AppDelegate.m file.
  2. In application:didFinishLaunchingWithOptions: add [Upsight setDefaultLogLevel:UpsightLoggerLevelDebug]; This will let you see the SDK's debug output while you confirm the integration. Once you have finished the integration, you can remove this line.

If you run the app now, you’ll see debug output showing SDK activity in XCode's debug console.

After finishing basic integration:

  • Running the app will generate an "upsight.config.expired" message.
  • The server will send a response to this message. The response body defines the configuration for the SDK. You will see the response JSON in the debug console.

Sessions are being tracked, and session-based metrics will be available:

  • Starting the app will generate an "upsight.session.start" message.
  • Stowing the app will generate an "upsight.session.pause” message.
  • When the app returns to the foreground an "upsight.session.resume" message is generated if you have been in the background for less than the configured session gap time (set by the server). Otherwise, a new "upsight.session.start" is sent, and the session ID is updated.
  • With the exception of the upsight.session.start and upsight.config.expired messages, these messages are batched and sent together: they will not show up on the dashboard immediately. You'll see a message like this in the debug window when the batch of events are sent: "batch queue sending batch to endpoint: http://batch.upsight-api.com/batch/v1/"

Since the dashboard takes time to process the messages, to track these messages in real time and ensure proper integration go to Real Time. Go to Real Time > Select App > Click on Filter.

Integration Center

Getting Started

Checking Console Logs


To check Console logs for iOS devices use Xcode. It can be downloaded online directly from Apple's App Store. Hook your device up to your computer via USB cable, run Xcode and navigate to Windows > Devices > "Your iOS device". Click the triangle in the bottom left hand corner of the device window in Xcode to show console logs.

Getting Started

Custom Events


Custom events are easier than ever to implement now. Once you have initialized the library, you can track an event just by setting the event name and properties.

To add a custom event:

  1. In your view controller’s .m file, add #import <UpsightKit/UpsightKit.h>
  2. At the point where you want to send the event, add

[Upsight recordAnalyticsEventWithName:@"event_name" properties:@{ @"Age": @"42", @"Gender": @"Male"}];

Set properties to nil if there are no properties you want tracked. Otherwise create an NSDictionary representing the event properties you wish to track. Examples include user's age, gender, or plan type. Additionally, for custom events periods can be used in the event name to create event hierarchy such as category.subcategory.my_event_name.

Note The debug console will now show the event has been stored. However until a sufficient number of events has been accumulated, or the batch of messages has reached a certain age, the messages will not actually be transmitted to the server. This will help improve the end user's network performance and battery life.

Getting Started

Milestones and Billboards - Getting and Showing Content


Getting and Showing Content

Milestones

Milestones are a new way to track user movement through your app and allow you to manage exactly when and where a user sees content. Milestones are triggered when your user reaches a point in your application that you want to track or take action on. After a user hits a Milestone of a given scope, the user will be able to see content from an open Billboard that also has that same scope.

To set a milestone, simply call the following function and assign a scope:

[Upsight recordMilestoneEventForScope:@"main_menu"];

Milestones have one required property - a "Scope" that uniquely describes that location in your application. Examples of Scope are "main_menu", "inventory", or "level_up". Additionally Milestone can track event properties by using a NSDictionary:

[Upsight recordMilestoneEventForScope:@"main_menu" properties:@{ @"Age": @"42", @"Gender": @"Male"}];

After Milestones are implemented within the app, they need to be registered in the dashboard. To navigate there go to Settings > Applications > App Name > App Settings > Milestones > Add Milestone.

Milestones

“Milestone scope” is what you called the milestone in your app. “Description” is just used to help you differentiate them.

Important "Scope" is a user defined String that must be all lowercase with no spaces.

Billboards

In order to display marketing content, a 'Billboard' must exist and be open. A billboard is like an empty frame into which the SDK can place content it receives from the server as a response to a milestone call. Like milestone events, each billboard is associated with a Scope. The content returned after a Milestone event will have the same Scope as the Milestone.

There are three basic steps to show content:

  1. Add the USBillboardDelegate protocol to one of your classes and implement presentingViewControllerForBillboard:
  2. Record a Milestone event for the scope.
  3. Get the USBillboard instance for the scope in which you want to show content, and set its delegate property to point at an instance of the class from step 1.

After Billboards are implemented within the app, a Campaign will need to be created in the dashboard before content will be shown.

Important By changing when your code starts performing steps 2 and 3 above, you can control when your content will be shown. Steps 2 and 3 do not need to be performed in a particular order, and content won't be shown until both steps have been performed. This allows you to control content freely. Additionally, you can use the isContentReady method to check that content was delivered for a given milestone and is ready for display before even opening up a billboard.

Example 1: Showing a Billboard in a View Controller

Change the ViewController’s interface definition to indicate that it implements USBillboardDelegate. This requires a <USBillboardDelegate> at the end of the View Controler’s @interface directive at the top of the .m file:

@interface ViewController () <USBillboardDelegate>

Add the following method:

-(UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard
{
    return self;
}

In the View Controller’s viewDidAppear: method get the USBillboard for your scope:

id <USBillboard> billboard = [Upsight billboardForScope:@“your_scope_name”];  
billboard.delegate = self;

Finally, send the Milestone:

[Upsight recordMilestoneEventForScope:@“your_scope_name”];

From the billboardDidDismiss callback, clear your billboard delegate to avoid more than one content item being shown at once (optional):

billboard.delegate = nil;

Example 2: Showing a Billboard in a Custom Class

In this example, content will be shown whenever MyClass's anInterestingMethod is called

@implementation MyClass

- (instancetype)init
{
    self = [super init];
    if (nil != self) {

        // Get the billboard for the scope
        id<USBillboard> billboard = [Upsight billboardForScope:@"SomethingInteresting"];

        // Set this object as the billboard's delegate
        // so the billboard can call presentingViewControllerForBillboard:
        billboard.delegate = self;
    }
    return self;
}


- (void)anInterestingMethod
{
    // Send a Milestone event here because something intersting happened
    [Upsight recordMilestoneEventForScope:@"SomethingInteresting"];
}


#pragma mark USBillboardDelegate methods

- (UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

@end

Push

Prerequisites


Setting Up for Push Notifications

If you have a push-enabled App ID and a production push certification, then you can skip the Prerequisites and precede to integrating Push.

Setting Up App ID and Certificates

  1. Login to your Apple Developer's Account.

  2. Click the Identifiers Portal under iOS Apps.

  3. Find the App ID and select edit or select the "+" button the top right corner to add a new App ID.

    Edit App

  4. Click the checkmark box next to Push Notifications and click Create Certificate for the environment you are implementing push on.

    Create Certificate

Production and Development Environments

To develop and deploy an application that supports push notifications, you must get SSL certificates from the appropriate Dev Center. Each certificate is limited to a single application, identified by its bundle ID. Each certificate is also limited to 1-2 development environments:

  • Development: Use the development environment for initial development and testing of the provider application.
  • Production: Use the production environment when building the production version of the provider application.

You must get separate certificates for the development environment and the production environment. The certificates are associated with an identifier of the application that is the recipient of push notifications; this identifier includes the application’s bundle ID.

Enabling Push Notification Service

  1. Follow the instructions to create a Certificate Signing Request (CSR) file and hit continue.

    Create Certificate

  2. Upload the .certSigningRequest file you just create and generate your iOS Push Certificate and hit continue.

  3. Download the file and double click to install the certificate to your Keychain Access Utility.

  4. When you finish those steps, the push notification service will be enabled in your iOS App ID settings as illustrated in the screenshot below.

    iOS App ID settings

SSL Certificate and Key

You should upload the SSL distribution certificate (or development certificate if you are using the development environment) and private cryptographic key to the Push Dashboard so that Upsight servers can connect with Apple's Push Notification service. To obtain your SSL APNS Certificate, follow these steps:

  1. Open the Keychain Access utility and click the My Certificates category in the left pane. Keychain Access Utility

  2. Find the certificate you just downloaded and installed to your Keychain Access. The certificate you are interested in should resemble the certificate shown in the above screenshot.

  3. Select the certificate and click File, Export Items. Export the certificate as a Personal Information Exchange (.p12) file.

To upload your certificate to the Push Dashboard, see the Push Interface section.

Setting Up and Installing the Provisioning Profile

The provisioning profile is a collection of assets that associates developers of an application and their devices with an authorized development team and enables those devices to be used for testing. The profile contains certificates, device identifiers, the application’s bundle ID, and all entitlements, including <aps-environment>. All team members must install the provisioning profile on the devices on which they will run and test application code.

To setup and install the provisioning profile, team members should complete the following steps shown in the table below.

  1. Login to your Apple Developer's Account.

  2. Go to the Provisioning Portal under iOS Apps.

  3. Download the provisioning profile associated with the application that is going to be tested or select the "+" button the top right corner to add a new Provisioning Profile.

    Provisioning Profile

  4. Double click the downloaded .mobileprovision profile file or drag it on to the Xcode or iTunes application icons to install. Alternatively, you can move the profile file to ~/Library/MobileDevice/Provisioning Profiles. Create the directory if it does not already exist.

  5. In the Xcode Organizer window, go to the Provisioning Profiles section and install the profile on your device. If using Xcode 6 navigate to the Xcode Devices window instead. Additionally remember to set your Provisioning Profile under Code Signing within your Build Settings.

Push

Integration Push


Push is supported through the USPush interface. Pushed content is displayed through a Push-specific billboard which is managed by the USPush interface. To integrate push, you must:

  1. Check 'Remote notifications' from the list of Background Modes in the Capabilities section of your target's settings.

  2. Add the USBillboardDelegate and UNUserNotificationCenterDelegate protocols to your App Delegate as well as import UserNotifications.h.

    #import <UserNotifications/UserNotifications.h>
    @interface AppDelegate () <USBillboardDelegate, UNUserNotificationCenterDelegate>`
    
  3. Implement the presentingViewControllerForBillboard: method in your App Delegate.

    - (UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard {
    
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;
    
        while (topController.presentedViewController) {
            topController = topController.presentedViewController;
        }
    return topController;
    }
    
  4. Register for push by calling [USPush registerForPushNotifications] in your App Delegate's didFinishLaunchingWithOptions: method, on iOS 10+, also set the Notification Center delegate.

    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        if ([[[UIDevice currentDevice] systemVersion] compare:@"10.0" options:NSNumericSearch] != 
        NSOrderedAscending)
        {
            [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
        }   
        [USPush registerForPushNotifications];
    return YES;
    }
    
  5. Call the USPush API method didRegisterUserNotificationSettings: in your App Delegate's application:didRegisterUserNotificationSettings: method.

     - (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    
    [USPush didRegisterUserNotificationSettings:notificationSettings];
    
    }
    
  6. Call the USPush API method registerPushToken: from didRegisterForRemoteNotificationsWithDeviceToken:

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    [USPush registerPushToken:deviceToken];
    
    }
    
  7. When a remote notification is received, set the USPush billboard's delegate to be your App Delegate class and call the USPush interface's handleRemoteNotificationWithUserInfo: method.

    - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [USPush pushBillboard].delegate = self;
    [USPush handleRemoteNotificationWithUserInfo:userInfo];
    
        if (NULL != completionHandler) {
            completionHandler(UIBackgroundFetchResultNoData);
          }
    }
    
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:
    (UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
    {
        [USPush pushBillboard].delegate = self;
        [USPush handleRemoteNotificationWithUserInfo:response.notification.request.content.userInfo];
    
        if (NULL != completionHandler) {
            completionHandler();
        }
    }
    

Note Once you have called USPush registerPushToken: the SDK will send an upsight.com.register message to the server containing your token. You can see this message through the Real Time dashboard.

Push

Sample AppDelegate


Here is a sample AppDelegate implementation that properly integrates Push

@interface AppDelegate () <USBillboardDelegate, UNUserNotificationCenterDelegate>
@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        if ([[[UIDevice currentDevice] systemVersion] compare:@"10.0" options:NSNumericSearch] != 
        NSOrderedAscending)
    {
        [[UNUserNotificationCenter currentNotificationCenter] setDelegate:self];
    }

        [USPush registerForPushNotifications];


    return YES;
}

- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [USPush didRegisterUserNotificationSettings:notificationSettings];
}

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    [USPush registerPushToken:deviceToken];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
    [USPush pushBillboard].delegate = self;
    [USPush handleRemoteNotificationWithUserInfo:userInfo];

        if (NULL != completionHandler) {
            completionHandler(UIBackgroundFetchResultNoData);
        }
}

- (void)applicationWillResignActive:(UIApplication *)application {
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
}

- (void)applicationWillTerminate:(UIApplication *)application {
}

#pragma mark - Billboard delegate

- (UIViewController *)presentingViewControllerForBillboard:(id<USBillboard>)aBillboard
{
    UIViewController *topController = [UIApplication sharedApplication].keyWindow.rootViewController;

    while (topController.presentedViewController) {
        topController = topController.presentedViewController;
    }

    return topController;
}

    #pragma mark - Notification Center Delegate
    - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:
       (UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler
    {
     [USPush pushBillboard].delegate = self;
     [USPush handleRemoteNotificationWithUserInfo:response.notification.request.content.userInfo];

      if (NULL != completionHandler) {
         completionHandler();
       } 
    }

@end

Push

Image Push


Overview

On iOS 10 and above, developers can use Upsight to send push notifications containing rich media such as images and gifs. In order to take advantage this, a few simple integration steps are required. Upsight currently supports image push for the following image formats: JPG,JPEG, PNG, GIF and SDK versions 4.3.2 and above.

To get started:

Add a new Target to your Xcode Project by navigating to the Target Template Selection screen by clicking File -> New -> Target. Once on the screen select the Notification Service Extension icon shown below and press Next. When choosing options for your Target, make sure ‘Language’ is set to Objective-C and ‘Embed In Application’ is set to the correct application.

Extension Selection

Notification Service Extensions have a separate Bundle ID from your application. In order to account for the new Bundle ID, you must generate a separate App ID and Provisioning Profile for the Notification Service Extension on the Apple Developer Portal.

Once your Notification Service Extension is created, Xcode will add a folder named with the product name designated when creating the Target. Inside this folder you will need to locate the NotificationService.m file and add the following code:

#import "NotificationService.h"
#import "Upsight.h"

@interface NotificationService ()

@property (nonatomic, strong) void (^contentHandler)(UNNotificationContent *contentToDeliver);
@property (nonatomic, strong) UNMutableNotificationContent *bestAttemptContent;

@end

@implementation NotificationService

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
    self.contentHandler = contentHandler;
    self.bestAttemptContent = [request.content mutableCopy];

    // Get a reference to the Upsight data in the push payload
    NSDictionary * inPushPayload =  request.content.userInfo[@"upsight_push_data"];

    if(nil != inPushPayload && [inPushPayload isKindOfClass:[NSDictionary class]] ) {
        NSMutableDictionary * outPushPayload = [[NSMutableDictionary alloc] initWithDictionary:inPushPayload];
        // Create a string with the Image URL passed down in the
        // Upsight payload using the key "media_url"
        NSString * imgString = inPushPayload[@"media_url"];

        // If an image is contained in the payload, the code below will
        // Manage the downloading and displaying of the image in the push.
        if(nil != imgString && [imgString isKindOfClass:[NSString class]]) {
            NSURL * imgURL = [NSURL URLWithString:imgString];

            [[[NSURLSession sharedSession] downloadTaskWithURL:imgURL completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                // If the download is successful a copy of the data will be stored in a
                // temporary directory where the data can be used to display the push
                if(nil != location) {
                    NSString * aTmpDir = NSTemporaryDirectory();
                    NSString * aTmpFileString = [imgURL lastPathComponent];

                    NSURL * theTmpUrl = [NSURL URLWithString:[[@"file://" stringByAppendingString:aTmpDir] stringByAppendingString:aTmpFileString]];

                    bool didMove = [[NSFileManager defaultManager] moveItemAtURL:location toURL:theTmpUrl error:nil];
                    if(didMove) {
                        // The image is added to the push as an attachment.
                        UNNotificationAttachment * theAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"USPushAttachment" URL:theTmpUrl options:nil error:nil];
                        self.bestAttemptContent.attachments = @[theAttachment];
                    }
                }
                else if(error) {
                    //  Uncomment this log if you are having issues with rich pushes.
                    //  NSLog("Error downloading file with Error:%@",error);
                    outPushPayload[@"error"] = error;
                    self.bestAttemptContent.userInfo = outPushPayload;
                }
                // Pass back the content handler that will display the push notification
                self.contentHandler(self.bestAttemptContent);
            }] resume];
        }
        else {
            // Append error details to the push payload
            outPushPayload[@"error"] = [NSError errorWithDomain:@"USPushDomain" code:0 userInfo:@{NSLocalizedDescriptionKey:@"No media URL in push payload"}];
            self.bestAttemptContent.userInfo = outPushPayload;
            self.contentHandler(self.bestAttemptContent);
        }
    }
    else {
        self.contentHandler(self.bestAttemptContent);
    }
}

- (void)serviceExtensionTimeWillExpire {
    // Deliver your "best attempt" content, otherwise the original push payload will be used.
    self.contentHandler(self.bestAttemptContent);
}

@end

Note Don’t forget to build and run your code before attempting to send a test push.

When adding a creative to your push notification, you will have the option to upload an image, which will be stored on Upsight’s CDN and delivered to the targeted devices upon request.

GDPR

Location


Upsight allows you to manually set both a user's home location and current location rather than relying on IP address. This is especially applicable for countries covered by the GDPR. If current or home country are manually set, they override any derived country information that would otherwise attribute a user to a specific country for reporting and targeting purposes.

Current Country

setCurrentCountry allows you to specify any 3-character country code to set as the user's current country. If you would like to clear this value, simply pass nil.

getCurrentCountry returns the set current country string of the user or nil if none was set.

Current country takes precedence over any derived country information (eg from IP).

Home country

setHomeCountry allows you to specify any 3-character country code to set as the user's home country. If you would like to clear this value, simply pass nil.

getHomeCountry returns the set home country string of the user or nil if none was set.

Home country takes precedence over current country and any derived country information.

Session Lifecycle Callbacks

Session Callbacks


To receive optional callbacks when an Upsight Session starts or resumes you must do the following:

  1. Add #import <UpsightKit/UpsightKit.h at the top of your AppDelegate.h file.
  2. Set your application delegate to implement the UpsightSessionDelegate protocol: @interface AppDelegate : UIResponder <UIApplicationDelegate, UpsightSessionDelegate>
  3. Add the following line to the top of your application:didFinishLaunchingWithOptions: method: [USSessionInfo setUpsightSessionDelegate:self];
  4. Implement any of the optional callbacks from UpsightKit/USSessionInfo.h

There are four Upsight session callbacks:

  1. upsightSessionWillStart - triggered when a new session, as defined by the Upsight SDK is about to start. Useful for setting user attributes before any events are sent to Upsight. It is not safe to trigger events. Passes an USSessionInfo object with information about the previous session.
  2. upsightSessionDidStart - triggered when a new session has finished starting. Useful for sending events immediately when a new session starts.
  3. upsightSessionWillResume - triggered when a session is going to resume. Useful for setting user attributes before any events are sent to Upsight. Also passes an USSessionInfo object with information about the current session. It is not safe to send events during this time.
  4. upsightSessionDidResume - triggered when a session has finished resuming. Useful for sending events immediately

Below is an example implementation:

In your AppDelegate.h:

// AppDelegate.h
//Add the following code in addition to the standard Upsight implementation
#import <UpsightKit/USSessionInfo.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate, UpsightSessionDelegate>

In your AppDelegate.m:

//AppDelegate.m
// A minor addition to didFinishLaunchingWithOptions
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [USSessionInfo setUpsightSessionDelegate:self];
...
}
// Add the new session callbacks that you'd like
- (void)upsightSessionDidStart
{
    // Now we can safely call a milestone
    [Upsight recordMilestoneEventForScope:@"game_launch"];
}
- (void)upsightSessionDidResume
{
    [Upsight recordMilestoneEventForScope:@"game_resume"];
}

Content Callbacks

Content Callbacks


Important Please note that the Content Callbacks are only available in Upsight SDK 4.7 and above.

To receive optional callbacks when Upsight content is available you must do the following:

  1. #import <UpsightKit/UpsightKit.h.
  2. Set implement the UpsightContentAvailabilityListener protocol eg in a ViewController: @interface ViewController () < ... , UpsightSessionDelegate>
  3. Set (setContentAvailabilityListener) and clear (clearContentAvailabiltyListener) the content listener where appropriate, eg in viewWillAppear and viewWillDisappear if in a ViewController.
  4. Implement any of the optional callbacks detailed below.

There are three Upsight Content callbacks:

  1. partnerInitialized:(NSString *)scope - triggered when a partner SDK has completed initialization. This is especially useful when calling scopes specific to mediated content. The mediation component's partner name is "fuse".
  2. onContentAvailableForScope:(NSString *)scope withParameters:(NSDictionary *)parameters - triggered when content becomes available for the given scope.
  3. onContentNotAvailableForScope:(NSString *)scope withParameters:(NSDictionary *)parameters - triggered when content fails for a given scope such as in the rare case if content is received but fails to build.

Below is an example implementation:

In ViewController.m:

//ViewController.m
@interface ViewController () <... UpsightContentAvailabilityListener>
//Register the listener 
- (void)viewWillAppear:(BOOL)animated
{
    ...
    [Upsight setContentAvailabilityListener:self];

}

//Unregister listener
- (void)viewWillDisappear:(BOOL)animated
{

    [Upsight clearContentAvailabiltyListener];

    ...
}


// Add the callbacks that you'd like
- (void) onContentAvailableForScope:(NSString *)scope withParameters:(NSDictionary *)parameters
{
    // Now we could open a billboard and know it will show immediately

}

- (void) onContentNotAvailableForScope:(NSString *)scope withParameters:(NSDictionary *)parameters
{
    // Now we could make a new milestone request for the scope
}

- (void) partnerInitialized:(NSString *)partnerName
{
    // Now we know we can make milestone requests that are dependent on the partner being initialized
}

User Attributes

User Attributes


User Attributes are properties you define which appear on every event sent to the Upsight servers. To implement User Attributes, you must first define the attributes in the Info section of your project's settings.

  1. Add a new row to your project's Info list and name it UpsightUserAttributes.
  2. Set the new row's type to Dictionary.
  3. Click on the disclosure triangle to the left of UpsightUserAttributes.
  4. Add a new row for each of the User Attributes you want to include, providing a name, type, and default value for each

Note If you would like to send null for a date attribute as a default you will have specify the following date 9999-12-31T23:59:59Z.

You can retrieve and set values for the User Attributes you have created within your code. You can access them by name. Assuming you used the preceding steps to create attributes called 'myNumberAttribute', 'myStringAttribute', myDateAttribute, and myBoolAttribute with types Number, String, Date, and Bool respectively, you would retrieve their values with the following:

NSNumber *aNumber = [USUserAttributes numberForKey:@"myNumberAttribute"];
NSString *aString = [USUserAttributes stringForKey:@"myStringAttribute"];
NSDate *aDate = [USUserAttributes dateForKey:@"myDateAttribute"];
BOOL aBool = [USUserAttributes boolForKey:@"myBoolAttribute"]

This returns the default values as defined in the Info settings, unless you change the values, like this:

[USUserAttributes setNumber:@(10) forKey:@"myNumberAttribute"];
[USUserAttributes setString:@"aString" forKey:@"myStringAttribute"];
[USUserAttributes setString:@"aStringListItem1,aStringListItem2" forKey:@"myStringListAttribute"];
[USUserAttributes setDate:[NSDate date] forKey:@"myDateAttribute"];
[USUserAttributes setBool:YES forKey:@"myBoolAttribute"]

Now, NSNumber *aNumber = [USUserAttributes numberForKey:@"myNumberAttribute"]; will return 10, NSString *aString = [USUserAttributes stringForKey:@"myStringAttribute"]; will return aString, [USUserAttributes dateForKey:@"myDateAttribute"] will return the date and time when the setDate:forKey: method was called and [USUserAttributes boolForKey:@"myBoolAttribute"] will return YES

Once you have set User Attributes in your code, add it as a Custom Attribute in your dashboard under Settings > Applications > App name > Edit app > Custom Attributes. This will allow you to segment and create analytics using your User Attributes.

When creating Custom Attributes in the dashboard, select the type which matches the type defined in your Info.plist. For String attributes, you may select string or a list of strings. string attributes allow you do store and match on a single item, for example, Team, City or Gender. A list of strings allows you to store a list of items and then create segments based on whether or not that list contains, or does not contain, specific items. This could be used to store a list of purchases, subscriptions, or other items, and is a more effective way to match against set which may contain lots of different items than creating individual boolean attributes, one for each item in the list. Lists of strings should still be defined with the string type in your plist and should be composed by comma separating the items into a single string when you set the value.

Custom Attributes

Note You cannot programmatically add or remove User Attributes. They must be added and removed through the Info settings. Adding and removing User Attributes will cause a discontinuity in the data stored on Upsight's servers, so it is something you should do only with forethought and planning.

Virtual Goods Promotion (VGP) and Rewards

Virtual Goods Promotion (VGP) and Rewards


Granting Rewards and VGP Purchases

Virtual Goods Promotions (VGP) and Rewards are two types of content that can be set up through the dashboard and displayed in a billboard. These are different from other content units in that you, as a programmer, need to know whether or not the customer has accepted the offer.

In the event your user receives a reward or purchasable virtual good, you are notified through one of two optional methods of the billboard delegate protocol:

- (void)billboard:(id<USBillboard>)aBillboard didReceiveReward:
(id<USReward>)aReward;

- (void)billboard:(id<USBillboard>)aBillboard didReceivePurchase:
(id<USPurchase>)aPurchase;

Note In order to track a VGP conversion, the product_id sent in your IAP message must be identical to the the one set up on the Upsight dashboard.

By providing an implementation for one or both of these methods, your code is given the opportunity to take appropriate action based on what your user has done.

In the case of a VGP, it is likely you will need to broker a transaction between your user and Apple's App Store. Once that transaction is finished you can track the results using an InAppPurchase event.

Important Please note that the Reward Product Identifier provided by Upsight to your application will be in lower case and can only contain alphanumeric characters and underscores.

Validating Rewards

Upsight offers you the ability to callback directly to your server when a reward is granted for validation or to send over reward data from your device. You can read about configuring server to server reward callbacks here as well as validating Upsight sent messages here.

If you would like to validate the reward that the Upsight server has granted to the device, you can do so by sending reward signature data to your server and performing an operation on the contents. You can get the signature data which is stored as a JSON NSData object by calling aReward.signatureData.

This JSON object contains the product, sid, quantity, nonce, and signature of the reward. You use the product, sid, quantity, and nonce along with your app's secret_key to produce the signature provided in the payload on your server.

Below is a python example of reward verification:

import base64
import hashlib
import hmac


def validate_signature_data(signature_data, secret):
    """Validates the signature for Upsight rewards.

    >>> secret = 'YOUR_32_CHAR_SECRET_KEY'
    >>> signature_data = {
    ...     'idfv': 'AAAAAAAA-0000-0000-0000-000000000000',
    ...     'nonce': '0437121572:rambo_cat:1',
    ...     'product': 'rambo_cat',
    ...     'quantity': 1,
    ...     'sid': '10000000000000000000',
    ...     'sig4': 'joQiupsyEe10Ui83TCPuScVBfOo',
    ...     'token': 'YOUR_APP_TOKEN'
    ... }
    >>> validate_signature_data(signature_data, secret)

    If the signature is invalid, or there is a problem with the signature_data
    dictionary, ValueError will be raised:

    >>> signature_data['sig4'] = 'invalid'
    >>> validate_signature_data(signature_data, secret)
    Traceback (most recent call last):
      ...
    ValueError: incorrect signature

    :param dict signature_data: A dictionary of signature data, from the SDK.
    :param str secret: Your app secret string.
    :raises ValueError: if the signature is invalid.
    """
    for required in ('nonce', 'sig4', 'token'):
        if required not in signature_data:
            raise ValueError('signature_data is missing {}'.format(required))

    identifiers = {}
    for identifier in ('device', 'gid', 'ifa', 'mac', 'odid', 'odin',
                       'idfv', 'sid'):
        value = signature_data.get(identifier)
        if not value:
            continue
        if isinstance(value, unicode):
            value = value.encode('utf8')
        identifiers[identifier] = value
    if not identifiers:
        raise ValueError('signature_data is missing identifiers')

    message = ':'.join((':'.join(str(identifiers[key])
                                 for key in sorted(identifiers.keys())),
                        signature_data['token'],
                        signature_data['nonce']))
    signature_hash = hmac.new(str(secret), message, hashlib.sha1)
    signature = base64.urlsafe_b64encode(signature_hash.digest()).rstrip('=')
    if not hmac.compare_digest(signature_data['sig4'], signature):
        raise ValueError('incorrect signature')

Native Messaging

Overview


Native Messaging lets you leverage Upsight’s Segmentation and Targeting to deliver campaigns where you can implement your own native display, instead of using one of Upsight’s interstitial campaigns.

Note Native Messaging is supported on Upsight SDK versions 4.4.0 and above.

Native Messaging campaigns are delivered through Milestones and Billboards as with our other campaigns types, plus your own handling of the returned data. See the Milestones and Billboards section for the core concepts, and the below instructions for the additional steps required to start using Native Messaging.

Native Messaging campaigns are designed to create native experiences by collecting the inputs required to build a desired experience then sending that data to the correct devices at the correct times. Before a Native Messaging campaign is published, the application source code will need to be updated to handle and/or display the expected payload inputs. Once a campaign has been triggered and a payload has been passed back, it is up to the developer to have the infrastructure in place to handle and display their intended experience. This responsibility includes using Upsight provided helper methods and objects to track events such as clicks and impressions, as well as controlling the destruction of campaign content.

The Upsight SDK provides several methods to access the data contained in a payload and will return native objects when possible. These accessor methods are made available through USDataPayload objects. USDataPayload objects are an Upsight created object type with numerous Native Messaging specific capabilities. When a Native Messaging campaign is triggered, a USDataPayload object will be returned through a delegate method, where the developer can then access the contents of the USDataPayload object and build their experience.

Important Images are handled differently than the other supported data types. Images sent in a Native Messaging campaign are pre-fetched and stored on disk in order to reduce latency when rendering an image once a milestone is triggered. Pre-fetched images are accessed via a file path and can be handled in your source code using a USDataImage object along with the provided helper methods.

Native Messaging

Integrate For Native Messaging


Receiving Data From a Native Messaging Campaign

In the source file in which you would like to access a Native Messaging payload, simply import UpsightKit.h.

 #import <UpsightKit.h>

Add the following delegate method to in order to access your Native Messaging payload. This method will get called when a campaign with a native message payload is received. While the billboard itself will not render any content, it is still used to make the payload available.

-(void)billboard:(id<USBillboard>)aBillboard didReceiveData:(id<USDataPayload>)aDataPayload {

 }

Accessing Content in a Native Messaging Campaign Object

USDataPayload objects provide instance methods to access the different types of objects contained in the native message.

Accessor method signatures for payloads generated using the Basic input format:

- (nullable NSString *)stringValueForKey:(nonnull NSString *)aKey;
- (nullable NSNumber *)booleanValueForKey:(nonnull NSString *)aKey;
- (nullable NSNumber *)intValueForKey:(nonnull NSString *)aKey;
- (nullable NSNumber *)floatValueForKey:(nonnull NSString *)aKey;
- (nullable UIColor *)colorValueForKey:(nonnull NSString *)aKey;
- (nullable USDataImage *)imageForKey:(nonnull NSString *)aKey;

USDataImage is an object defined in USDataPayload.h and contains properties for the image's loaded-on-disk file path, width, and height. Please use this information to load the image into memory and display it as you see fit.

Native Messages created using the ‘Raw’ input method will can be accessed via the getRawData method. This method provides a dictionary containing raw data in the same structure and format as entered in the campaign on the Upsight Dashboard.

- (nullable NSDictionary *)getRawData;

Important After the billboard containing the native message is dismissed, all data associated with the returned USDataPayload will be removed. For USDataImage objects, this means that the image on disk that is being referenced will be deleted. Please make a separate local copy of any images that you would like to persist past the life of the billboard.

Tracking User Interaction

Once the Native Messaging campaign is ready to be displayed to the user, the interaction the user has with the campaign can be tracked by calling various methods on your USDataPayload object. The available methods are:

  1. - (void)recordImpressionEvent; - Send this once the content of the campaign is rendered and displayed to the user.
  2. - (void)recordClickEvent; - Send this if the user interacts with your campaign such as accepting a dialog prompt.
  3. - (void)recordDismissedEvent; - Send this once the campaign is no longer on screen.
  4. - (void)destroy; - Send once the payload is no longer needed, e.g. after the dismiss button has been pressed or after a user has performed the desired action. This method must be called to inform the SDK that the content interaction is finished.

Important If a campaign is not intended to be seen by users, simply call destroy on the payload once it has been processed by the application.

Native Messaging

Example


Here is a sample implementation of a Native Messaging campaign used to render a native interstitial within an application.

In order to have this example display the campaign on a device, a Native Messaging campaign was created on the dashboard by with the following inputs:

example screenshot 1

As well, to handle the expected payload from the Native Messaging campaign, the below implementation was added to the application intended to render the campaign:

- (void)billboard:(id<USBillboard>)aBillboard didReceiveData:(id<USDataPayload>)aDataPayload 
{
//Create USDataPayload object to access the data payload
USDataPayload *payload = (USDataPayload *)aDataPayload;

//Create a UIView to display the details contained in the USDataPayload object
UIView *contentDisplayView = [[UIView alloc]initWithFrame:CGRectMake(15, 450, 300, 150)];

//Add the body text to the display
UITextView *bodyCopy = [[UITextView alloc]initWithFrame:CGRectMake(40, 485, 120, 40)];
bodyCopy.text = [payload stringValueForKey:@"BodyCopy"];
[contentDisplayView addSubview:bodyCopy];

//Add a background color to the display
UIColor *backgroundColor = [payload colorValueForKey:@"BGColor"];
contentDisplayView.backgroundColor = backgroundColor;

//Pre-fetch and store images on disk to be accessed later through a file path
USDataImage * offerImage = [payload imageForKey:@"OfferImage"];
USDataImage * ornamentImage = [payload imageForKey:@"OrnamentImage"];

if(offerImage.imagePath && ornamentImage.imagePath) {
    //Retrieve images using file path and render in display
    UIImage *offerImageToRender = [UIImage imageWithContentsOfFile:offerImage.imagePath];
    UIImage *ornamentImageToRender = [UIImage imageWithContentsOfFile:ornamentImage.imagePath];
    if(offerImageToRender && ornamentImageToRender) {
        UIImageView *offerImageView = [[UIImageView alloc] initWithFrame:CGRectMake(215, 475, 100, 100)];
        offerImageView.image = offerImageToRender;
        UIImageView *ornamentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 580, 40, 40)];
        ornamentImageView.image = ornamentImageToRender;
        //Add imageViews to the display
        [contentDisplayView addSubview:offerImageView];
        [contentDisplayView addSubview:ornamentImageView];
    }
 }
if( nil != payload ) {
    [payload destroy];
 }
}

When a user reaches the appropriate milestone your Native Messaging payload will be delivered to the device. If handled correctly by the source code, the campaign creative will render an experience like this:

example screenshot 2

Native Messaging

Testing a Native Messaging Campaign


Once a native messaging campaign is configured in the dashboard and the application is set up to handle native messaging payloads simply trigger a milestone with the scope of the campaign and open a billboard. Depending on the implementation, the campaign should render and, when clicked, a content displayed, dismissed, and click should display in Upsight RealTime.

Upsight Ad Mediation

Prerequisites


Setting Up Upsight Ad Mediation

In order to set up the Upsight Ad Mediation SDK, you will need to have Upsight Ad Mediation added to your account and be on SDK version 4.1.1 or later. Contact your customer success manager for more information.

Upsight SDK Integration

Upsight Ad Mediation can only be used in conjunction with the base Upsight SDK and will show rewarded and non-rewarded video ads through billboards and milestones. Make sure you have completed the basic integration of the Upsight SDK including billboards and milestones before you begin integrating Upsight's Ad Mediation SDK.

Upsight Ad Mediation

Cocoapods


The Upsight Ad Mediation SDK can be installed via cocoapods. Before running a pod install inside your terminal, make sure you have Git LFS installed. This is required to for cocoapods to properly fetch our mediation framework. For instructions on how to install Git LFS, please refer to this page: https://help.github.com/articles/installing-git-large-file-storage/

Once Git LFS is installed, run a pod install inside your terminal, or from CocoaPods.app.

After Git LFS is installed, simply add pod 'UpsightAdMediation', '~> 2.12' similar to the following in your Podfile:

target 'MyApp' do
  pod 'UpsightAdMediation', '~> 2.12'
end

You will also have to add the following to your Info.plist for iOS 10 as some ad networks access these features:

<key>NSCalendarsUsageDescription</key>
<string>Advertisement would like to create a calendar event.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Advertisement would like to store a photo.</string>
<key>NSCameraUsageDescription</key>
<string>Advertisement would like to use your camera.</string>
<key>NSMotionUsageDescription </key>
<string>Advertisement would like to use motion for interactive ad controls</string>

If you are upgrading from 4.2 or earlier, please ensure you remove libUpsightMediation.a as it is no longer required.

Once this is complete, you can proceed to the Showing Mediated Video Ads section.

Upsight Ad Mediation

Manual Integration


Downloading the SDK

Before staring the integration, you'll need to download the latest Upsight Ad Mediation Framework. You can download the iOS version here.

Importing

After downloading, import the Upsight Ad Mediation Framework by dragging and droppingUpsightMediation.framework into your project.

If you have a previous version of Upsight Mediation, you will have to remove the following files when upgrading:

UpsightAdMediation.h
UpsightAdMediationDefinitions.h
libUpsightMediationAds.a
libUpsightMediation.a (4.2 and below)

Project Configuration

Required Frameworks

The Upsight Ad Mediation SDK requires these frameworks to be included in addition to the base frameworks required by the Upsight SDK:

  1. SafariServices.framework (weak link)
  2. Accelerate.framework
  3. AudioToolbox.framework
  4. AVFoundation.framework
  5. CoreGraphics.framework
  6. CoreLocation.framework
  7. CoreMedia.framework
  8. EventKit.framework
  9. EventKitUI.framework
  10. Foundation.framework
  11. GameKit.framework
  12. libsqlite3.tbd
  13. libxml2.tbd
  14. libz.tbd
  15. MediaPlayer.framework
  16. MessageUI.framework
  17. MobileCoreServices.framework
  18. QuartzCore.framework
  19. Social.framework (weak link)
  20. StoreKit.framework
  21. SystemConfiguration.framework
  22. Twitter.framework
  23. UIKit.framework
  24. WebKit.framework
  25. GLKit.framework
  26. CoreMotion.framework
  27. JavascriptCore.framework (weak link)
  28. WatchConnectivity.framework (weak link)

Disabling ATS and BitCode

AppTransportSecurity

Some of the ad network SDKs used by the Upsight Ad Mediation SDK do not support sending their data over HTTPS. If you are building on XCode 7, you must turn off App Transport Security by adding an additional dictionary item to your Info.plist. To so, add a dictionary item in your Info.plist called NSAppTransportSecurity with a boolean item NSAllowsArbitraryLoads set to YES. You can view more information this specific setting on Apple's documentation website.

BitCode

While the Upsight and UpsightAdMediation SDK are built with bitcode enabled, some of the included ad network libraries have not yet enabled bitcode. You can manually disable bitcode in your application by going to the Build Options in your target's build settings and setting Enable Bitcode to No.

iOS 10 Privacy Settings

With the release of iOS10, Apple made it a requirement to define the usage description for references to classes that are associated with permission-related objects. Some networks that are mediated make use of these permissions. For your submitted app to be approved, the following entries must be added to your Info.plist:

<key>NSCalendarsUsageDescription</key>
<string>Advertisement would like to create a calendar event.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Advertisement would like to store a photo.</string>
<key>NSCameraUsageDescription</key>
<string>Advertisement would like to use your camera.</string>
<key>NSMotionUsageDescription </key>
<string>Advertisement would like to use motion for interactive ad controls</string>

Upsight Ad Mediation

Showing Mediated Video Ads


Non Rewarded Video Ads & Static Interstitials

Once you have added the SDK, you will be able to show a mediated video ad or static interstitial at any billboard. Simply go to your Upsight Dashboard and create an Ad Campaign targeting a specific milestone. See the Creating Mediated Ad Campaigns section for more information.

Rewarded Video Ads

Simply implement handling rewards and you will be able to grant your users rewards when running a Rewarded Video Ad campaign at any billboard for a given milestone scope.

Make sure to add the rewards to the dashboard. See Adding Rewards for more information.

Monetization

Monetization


Upsight makes it easy to track and analyze revenue you earn from customers with monetization events. There are two separate methods that you can use to track monetization. If you wish to track a purchase made through the App Store, use the following method from the Upsight class:

 + (void)recordInAppPurchaseEventWithResolution:(USPurchaseResolution)resolution
 product:(NSString *)product
 quantity:(NSUInteger)quantity
 price:(float)price
 currency:(NSString *)currency
 transactionIdentifier:(NSString *)transactionIdentifier;
  • resolution - one of:

    • USPurchaseResolutionBuy if the purchase was successful.
    • USPurchaseResolutionCancel if the user canceled the purchase.
  • product - The product name, as provided by the productIdentifier property of an SKProduct object.

  • quantity - The number of products purchased during the transaction, as set in the quantity property of an SKPayment object.

  • price - the value returned by price.floatValue where price is the price property of an SKProduct object.

  • currency - the value returned by [priceLocale objectForKey:NSLocaleCurrencyCode] where priceLocale is the priceLocale of an SKProduct object.

  • transactionIdentifier - A value extracted from the SKTransaction object sent by Apple during the StoreKit exchange.

When the SDK sends an InAppPurchase event recorded with this method, it attaches the receipt object from the transaction with the App Store. The Upsight server then validates this receipt with the Apple servers.

If you have a purchase to record that did not involve the Apple store, you can use this method instead:

+ (void)recordMonetizationEventWithTotalPrice:(float)totalPrice currency:
(NSString *)currency;
  • totalPrice - the total amount of the transaction.

  • currency - typically retrieved using [[NSLocale currentLocale] objectForKey:NSLocaleCurrencyCode].

Location Tracking

Location Tracking


Enabling location tracking will allow you target and segment your users based on their geographical location. That data will be attached to all the events sent from the device. To provide the SDK with location data, first configure location services in your application.

CLLocationManager *locationManager = [[CLLocationManager alloc] init];
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate = self; // something that implements CLLocationManagerDelegate
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.distanceFilter = 1.0;
[locationManager requestWhenInUseAuthorization];
[locationManager startUpdatingLocation];

Then implement the following CLLocationManagerDelegate method.

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *location = [locations firstObject];
    [Upsight setLocation:location];
}

Finally, add a row to your application's info.plist file with NSLocationWhenInUseUsageDescription as the key, and set the value as a string with text you want the application to display to users when they're asked for permission to use their location data.

The location you provide to the SDK will be used until it is updated, or until the user's session ends (the application is put into the background for more than two minutes).

It is good practice to have only one instance of CLLocationManager active at a time. When an instance of CLLocationManager goes out of scope you will cease to receive location updates, it is typically saved as a property in an active object instance.

It is also good practice to set the desiredAccuracy to the lowest value possible while still achieving your application's purpose. This is to prevent excessive use of system resources.

Managed Variables

Integration


This feature allows you to use Managed Variables in your application; these are variables whose values are set by the server. Managed Variables are referenced by tag.

To begin, you must declare your Managed Variables in a file called UpsightUXMVariables.plist

UXM plist screenshot

  • The default field should contain the value the Managed Variable should return if it has not been updated by the server.

  • The description field should contain a string that describes what the Managed Variable is used for.

  • The type field should define the type of the Managed Variable. Variables can be of type String, Number, or Boolean.

  • The tag field defines the name by which you will reference the variable in your code. Each tag must be unique within your app.

  • The max field is only used by number type variables. It defines the largest number value that the Managed Variable can return; any larger values will be replaced by this value.

  • The min field is only used by number type variables. It defines the smallest number value that the Managed Variable can return any smaller values will be replaced by this value.

In the source file where you want to access a managed variable, import the Upsight framework.

#import <UpsightKit/UpsightKit.h>

Then, call the USManagedVariable class method listed below that corresponds to the type of the managed variable you are accessing.

+ (id<USManagedString>)managedStringWithTag:(NSString *)aTag;
+ (id<USManagedInteger>)managedIntegerWithTag:(NSString *)aTag;
+ (id<USManagedFloat>)managedFloatWithTag:(NSString *)aTag;
+ (id<USManagedBoolean>)managedBooleanWithTag:(NSString *)aTag;

The returned object will have a value method appropriate to its type. The value method returns the most recent value retrieved from the server, or the default value if no value has been retrieved yet.

id<USManagedString> uxmString = [USManagedVariable managedStringWithTag:@"personage_name"];
NSLog(@"The current value of personage_name is %@", uxmString.stringValue);

If you wish to be notified when the system has updated the values of the Managed Variables, you can set a delegate on the variable observer:

[Upsight variableObserver].delegate = self;

The object you assign as the variableObserver's delegate must conform to the USManagedVariableObserverDelegate protocol. This call must be made no earlier than the call to your app delegate's applicationDidBecomeActive: method.

If you implement the optional observer:didSynchronizeManagedVariables: method, the Managed Variable observer will call your implementation immediately after all the managed variables have been updated. Included in this call is an NSArray containing the tags of all the variables that were updated.

If you keep any references to Managed Variables that you access before the call to observer:didSynchronizeManagedVariables: you need to refresh those references afterward in order to see the new values.

If you wish to prevent updates to the Managed Variables you can override observerShouldSynchronizeManagedVariables:. If you return NO from your implementation of this method none of the managed variables will be updated. This method is called every time a session starts, so you will have the chance to accept updates you previously rejected.

Attribution Tracking

Setting Attribution Source


With Upsight SDK version 4.2.0 and above, you can manually set an install attribution source with the recordAttributionEventForCampaign method:

[Upsight recordAttributionEventForCampaign:campaign creative:creative source:source properties:pub_data];

Helper Methods

isContentReady


Description

Returns true if there is content ready for a given scope.

Example

[Upsight billboardForScope:scope].isContentReady;

Helper Methods

senderID


Description

Invoke this method to get your Sid. Sid is an internal user identifier Upsight uses. In situations, you may want to use this identifier for your own internal purposes or store it on your servers.

Example

[Upsight senderID];

Helper Methods

getLatestSessionInfo


Description

A method that gets information about the current Upsight session by returning an USSessionInfo object. If no session is active, this method will return the most recent session information. If no session has been recorded, then a default USSessionInfo object with sessionNumber of nil, and sessionStartTime of 0 will be returned.

Example

[USSessionInfo getLatestSessionInfo];

Best Practice for Testing

Best Practice for Testing


Keeping your production data clean in Upsight is important to maintaining the data integrity of your most important metrics. To do this, it just takes a few steps to implement.

  1. First create Test and Production Applications in the Upsight Dashboard.

  2. Note each Application’s Token and Public Key.

  3. In XCode Go to Project Settings > Build Settings and click to add a User Defined Setting.

    User Defined Setting

  4. Set name as UPSIGHT_TOKEN and repeat to create UPSIGHT_PUBLIC_KEY.

  5. Expand each setting and enter values for Debug and Release configurations from Upsight Dashboard corresponding to Testing and Production applications copied from step 2.

    Token and Public Key

  6. Go to the Info section of Build Settings. Update UpsightAppToken to your $(UPSIGHT_TOKEN) and update UpsightAppPublicKey to your $(UPSIGHT_PUBLIC_KEY).

    Build Settings

Finding Device Identifiers

How to find your IDFA


Using Real Time

The easiest way to get a device's IDFA is by using Real Time in your dashboard once your app is integrated with the Upsight SDK.

Simply click on an event and search for ids.idfa. For example, the IDFA will look something like 236A005B-700F-4889-B9CE-999EAB2B605D.

Using Console Log

  1. Connect your device to your computer via USB cable.
  2. Check the console log on your computer. To learn how to check the console log, see the iOS console logs article.
  3. Open the app that you have integrated the Upsight SDK with.
  4. Search for ids.idfa in the console log.

By searching for the ids.idfa parameter in the console log, you can find the IDFA. For example, the IDFA will look something like 236A005B-700F-4889-B9CE-999EAB2B605D.

Note If the "Limit Ad Tracking" setting in Settings-> Privacy->Advertising is on, Upsight will ignore the IDFA sent, which effectively means the device will be unrecognizable to Upsight (i.e. it will be treated as a new device, it will not act as a test device even if it is registered as a test device with the proper IDFA, no user activity will be tracked, etc.)

You can also reset your IDFA from this screen. If you do a full hardware reset on your device, your IDFA will be reset to something else.

Finding Device Identifiers

How to find your IDFV


Using Real Time

The easiest way to get a device's IDFV is by using Real Time in your dashboard once your app is integrated with the Upsight SDK.

Simple click on an event and search for ids.idfv. For example, the IDFV will look something like C305F2DB-56FC-404F-B6C1-BC52E0B680D8.

Using Console Log

The easiest way to get a device's IDFV is by checking your console log while opening your app that is integrated with the Upsight SDK.

  1. Connect your device to your computer via USB cable.
  2. Check the console log on your computer. To learn how to check the console log, see the iOS console logs article.
  3. Open the app that you have integrated the Upsight SDK with.
  4. Search for ids.idfv in the console log.

By searching for the ids.idfv parameter in the console log, you can find the IDFV. For example, the IDFV will look something like C305F2DB-56FC-404F-B6C1-BC52E0B680D8.

COPPA

COPPA


If you operate a mobile app directed to children under 13 that collects, uses, or discloses personal information from children or you otherwise have actual knowledge that you are collecting, using, or disclosing personal information from children under 13, the Children’s Online Privacy Protection Act (COPPA) may apply to you. If so, you may have responsibilities relating to how you collect, disclose, or use personal information from such children.

To assist you in your data collection, disclosure and use compliance obligations, we have added to the platform a new "opt-out" setting to the iOS SDK, so you can indicate whether you want Upsight to limit data collection and use, and serve only contextually targeted ads.

Child-directed settings and features

  • A default value for the opt-out flag in the SDK that can be changed by the publisher. The default value out-of-the-box will be opt_out = FALSE.
  • Functionality in the SDK to change the opt-out flag for the individual user. Publisher may use this setting if it utilizes age-gating functionality, for example.

Example

If you have an app that is directed at 8-10 year olds, you can set the default value for the opt-out flag to be TRUE for all users. Then, you can add an age-gating mechanism to the app, and change the opt-out flag to FALSE for users that you learn to be 13 or older.

Targeting Opt-Out

To comply with COPPA regulations and standards, Upsight has provided a mechanism for your app to opt-out of collecting user information. The user opt-out status inside your app is indicated by

+ [Upsight optOutStatus]

Its value defaults to NO, which means that user data is sent by default.

To set the opt-out status for your app at runtime, use the following method:

+ [Upsight setOptOutStatus:(BOOL)trueOrfalse];

Although Upsight has enabled this functionality, you are still responsible for providing an appropriate user interface for user opt-out.

For official information about COPPA, the recent amendments, and a list of FAQs provided by the FTC, please consult the FTC website.