Apxor
IntegrationProduct Guides
  • Introduction to Apxor
  • Getting Started with Apxor
    • Adding a New App
    • Firebase Credentials (optional)
    • SDK
      • Android (x)
      • iOS SDK
      • iOS SDK (Swift UI)
      • iOS SDK (Manual)
      • Web npm based
        • Tracking Events and Pages for Web
      • Web URL based
        • Tracking Events and Pages for Web
      • React Native
      • Cordova
      • Flutter
      • Jetpack Compose
    • API Guides
      • iOS
      • Web
      • React Native
      • Cordova
      • Flutter
    • Release Notes
    • Performance
    • Troubleshooting
  • Product Guides
    • Integration Checklist
    • Create a Campaign
      • Mobile
        • Target
        • Trigger
        • Schedule and Limit
        • Review and Test
        • Set Priority and Publish
        • A/B Testing
        • Campaign Listings Page
        • Campaign Analytics
        • Campaign Designs
          • Tooltips
          • In-App Messages
          • Coachmarks
          • Badges
      • Web
        • Target
        • Trigger
        • Schedule and Limit
        • Review and Test
        • Set Priority and Publish
        • A/B Testing
        • Campaign Listings Page
        • Campaign Analytics
        • Web Templates
    • Create a Survey
      • Legacy
        • Target
        • Trigger
        • Schedule and Limit
        • Review and Test
        • Publish
        • Survey Listings Page
        • Survey Analytics
        • Survey Designs
          • Request for Survey
          • Single Response
          • Multi Response
          • Rating
          • Short Answer
          • Success Message
      • Latest
        • Survey Stop Conditions
        • Target
        • Trigger
        • Schedule and Limit
        • Review and Test
        • Publish
        • Survey Listings Page
    • Custom Reports
    • Analytics
      • Custom Dashboards
      • Uninstalls
      • Retention
      • Funnels
      • Paths
      • Event Analysis
    • BI Dashboard
      • Frequency
      • Aggregates
      • Trends
      • Pie Chart/Advanced Pie Chart
      • Table
    • Insights
      • Activation Analysis
      • Correlation Analysis
    • Adding a Test Device
    • Preview vs. Test vs. Publish
    • Dynamic Script
  • Partner Integrations
    • Mixpanel
    • MoEngage
    • Amplitude
    • CleverTap
  • Glossary of Terms
  • Video Gallery
  • Beta Features
    • Create Embedded Cards Campaign
    • Create Stories Campaign
Powered by GitBook
On this page
  • Getting started with Apxor iOS
  • Adding Apxor SDK to your project
  • Initialize Apxor iOS SDK
  • Auto initialize SDK (Recommended)
  • Manually initialize SDK (Not Recommended)
  • Configuring Test Device
  • Configure URL Scheme
  • Handling the deep link
  • Configuring Push Notifications
  • Embed Slot
  • Story Slot
  • Ensuring Apxor SDK is initialized successfully
  • Add-Ons
  • Initializing the SDK
  • Identifying the Users
  • Setting up campaign triggers, capturing data for targetting and goal tracking​
  • App Events​
  • User Attributes
  • Session Attributes
  • Client Events
  • Track Screens
  • Reporting Custom Errors
  • Custom Fonts
  • To get Apxor Device Identifier
  • Log Events inside WebView
  • Actions in WebView
  • Dynamic Script Text in actions
  • Yeah! You are ready to create your first Campaign or Survey
  1. Getting Started with Apxor
  2. SDK

iOS SDK

PreviousAndroid (x)NextiOS SDK (Swift UI)

Last updated 10 days ago

Things to keep handy before starting your integration with Apxor

Please have the following handy before beginning the integration:

  • Application identifier generated on the Apxor dashboard for your app ()

  • App Bundle Id : Every app has a unique application ID that looks like com.example.myapp. This id uniquely identifies the app on the device and also on the app store.

  • The list of events to setup triggers and track goals, user properties that allows to personalize messages and to target better. ()

Note

If you are already using a separate analytics class where you are sending events to different platforms from a single place it is much faster to use our tracking guide to complete event logging to setup triggers and track goals.

In case you are logging events to third parties after each interaction, please use our Third party API guide to migrate all the events that you are sending to one of the supported third parties as listed in the guide.

Getting started with Apxor iOS

Apxor provides you easy to use plugins for your Actions. They are:

Plugin Name
Description
Example

Apxor-Core

The Core Plugin is responsible for the basic event tracking

How many of my users have clicked on the cart icon after showing them a nudge Sample Event : 'ViewCart'

APXSurveyPlugin

This Plugin helps you create contextual surveys to capture your users' feedback, ratings, etc.

An NPS survey that would ask the user to rate the app experience on a scale of 1-10.

APXRTAPlugin

This Plugin helps you create real time actions.

Show a tooltip on the cart icon with messaging "Tap here to view items"

APXWYSIWYGPlugin

The WYSIWYG Plugin allows you to preview your configured actions onto your device in real time

Casting your mobile screen to the dashboard and selecting the hamburger icon

APXPushPlugin

The Push Plugin allows you to track uninstalls and real-time serve/pause the nudges, while the app is opened

Show a campaign to users who land on the home screen and add an item to the cart.

.

Adding Apxor SDK to your project

  • If this is your first pod, run pod init. Add the following to the corresponding target in your Podfile and run pod install.

use_frameworks!
pod 'Apxor-Core', '2.10.41'
pod 'Apxor-CE', '1.05.29'
pod 'Apxor-Push', '1.01.02'
pod 'Apxor-RTA', '1.09.43'
pod 'Apxor-WYSIWYG', '1.02.73'
pod 'Apxor-Survey', '1.04.22'

Initialize Apxor iOS SDK

Auto initialize SDK (Recommended)

  • To Auto initialize SDK (Recommended), add the following inside your application plist file.

  • Open your application's Info.plist as source code.

  • Copy paste the below piece of code, to create an entry for ApxorSDK.

<key>Apxor</key>
<dict>
    <key>Core</key>
    <string>YOUR_APP_ID</string>
    <key>APXSurveyPlugin</key>
    <true/>
    <key>APXRTAPlugin</key>
    <true/>
    <key>APXPushPlugin</key>
    <true/>
    <key>APXWYSIWYGPlugin</key>
    <true/>
</dict>

Manually initialize SDK (Not Recommended)

  • To manually initialize SDK, call ApxorSDK.initialize method in your Application class

//...
#import "ApxorSDK/ApxorSDK.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    [ApxorSDK initializeApxorWithID:@"<YOUR_APP_ID>"];
    // ... your code
}
  • And open your application's Info.plist as source code.

  • Copy paste the below piece of code, to create an entry for ApxorSDK.

<key>Apxor</key>
<dict>
    <key>APXSurveyPlugin</key>
    <true/>
    <key>APXRTAPlugin</key>
    <true/>
    <key>APXPushPlugin</key>
    <true/>
    <key>APXWYSIWYGPlugin</key>
    <true/>
</dict>

Note

To get your app ID, please email us at contact@apxor.com

Configuring Test Device

  • First, you need to configure your app to ensure there is a URL Scheme with your application's bundle identifier as the value.

  • If your app already has a URL Scheme with your application's bundle identifier as the value, you can skip this step.

Configure URL Scheme

  • To configure URL scheme, goto your project settings, select Targets. Click on the Info tab.

  • Select the URL Types, and click on the + button to add a new URL Scheme.

  • Add a new URL Scheme with your bundle identifier as the value.

  • Your bundle identifer will be in the format, com.xxxx.xxxx

  • Use the image below for reference.

Note

Make sure the URL scheme has the value of your bundle identifier that was provided in the dashboard while registering with us. Also, the app must have same bundle identifier.

Handling the deep link

Using AppDelegate
  • You'd need to enable Apxor to handle Apxor specific deeplinks.

  • In your application's AppDelegate file, in the function application(_:open:options:), add the following code at the beginning,

// ObjC
NSString *urlStr = url.absoluteString;
if ([urlStr containsString:@"add-test-device"]) {
  [ApxorSDK handleDeeplink:url];
}
// Swift
/*
  Apxor's code to handle deeplinks
  */
let urlStr = url.absoluteString
if (urlStr.contains("add-test-device")) {
    ApxorSDK.handleDeeplink(url)
}
  • This will ensure the Apxor specific deep links are handle by our SDK.

Using SceneDelegate
  • You'd need to enable Apxor to handle Apxor specific deeplinks.

  • In your application's SceneDelegate file, add the following code at the beginning,

// ObjC
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
  for(UIOpenURLContext *x in URLContexts) {
    NSURL *url = x.URL;
    if([[url absoluteString] containsString:@"add-test-device"])
    {
      [ApxorSDK handleDeeplink:url];
    }
    break;
  }
}
// Swift
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
  let url = URLContexts.first?.url
  let urlStr = url?.absoluteString
  if (urlStr!.contains("add-test-device")) {
    ApxorSDK.handleDeeplink(url!)
  }
}

Configuring Push Notifications

  • To use the push notifications feature, make sure the following lines exist in your application plist file under Apxor section.

<key>APXPushPlugin</key>
<true/>
  • To configure iOS Push notification via Apxor dashboard, you'd need to upload APNs Auth Key file along with it's ID (key ID), your Team ID, and your application's Bundle ID.

  • The APNs Auth Key is the best way to configure pushes, as you don't need to regenerate a certificate every year and also, this key can be used to configure Push notifications to sever of your applications (under the same apple developer account)

  • Things required to configure iOS Push notification:

  • Auth Key file

    • Key ID (usuallly the name of the Auth Key file)

    • Team ID (the 10 digit alphanumeric key)

    • Your app’s bundle ID (in the format com.abc.xyz)

    • See here on how to get these, Push notifications

  • Once you get those details, add the below code in your application's AppDelegate file in the application didRegisterForRemoteNotificationsWithDeviceToken function.

import APXPushPlugin

let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
APXPushPlugin.setPushDeviceToken(token)
[APXPushPlugin setPushDeviceToken:token];
  • The token can be passed in either the NSData or NSString format

  • If you haven't already used the code to Ask User for notifications permission, add the following function in your AppDelegate file.

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  // your existing code ...

  registerForPushNotifications()

  // ...
}

func registerForPushNotifications() {
  UNUserNotificationCenter.current()
    .requestAuthorization(options: [.alert, .sound, .badge]) { [weak self] granted, error in
      print("Permission granted: \(granted)")
      guard granted else { return }
      self?.getNotificationSettings()
    }
}

func getNotificationSettings() {
  UNUserNotificationCenter.current().getNotificationSettings { settings in
    print("Notification settings: \(settings)")
    guard settings.authorizationStatus == .authorized else { return }
    DispatchQueue.main.async {
      UIApplication.shared.registerForRemoteNotifications()
    }
  }
}

Embed Slot

Note

For using Apxor Embedded Cards the versions of the following plugins should be greater than or equal the ones mentioned below

Core: 2.10.26

RTA: 1.09.26

CE: 1.05.16

WYSIWYG: 1.02.67

For using Apxor's immersive template embedded cards, this step is necessary.

In all areas of the app where you may want to show an in-line widget, insert the following code in the view controller:

// Swift

let EmbedCard = APXRTAPlugin.initEmbedCard(withId: <Tag>)!

// you can add it in a UIStackView (recommended)
let stackView = UIStackView()
stackView.addArrangedSubview(EmbedCard)

// add your other existing views if any
stackView.addArrangedSubview(existingView1)
.
.

// if you want to add it in a UIView
let sampleView = UIView()
sampleView.addSubview(EmbedCard)

// add constraints (optional)
EmbedCard.translatesAutoresizingMaskIntoConstraints = false

EmbedCard.topAnchor.constraint(equalTo: sampleView.topAnchor).isActive = true
EmbedCard.leadingAnchor.constraint(equalTo: sampleView.leadingAnchor).isActive = true
EmbedCard.bottomAnchor.constraint(equalTo: sampleView.bottomAnchor).isActive = true
EmbedCard.trailingAnchor.constraint(equalTo: sampleView.trailingAnchor).isActive = true
// Objective-C

APXEmbedCard *embedCard = [APXRTAPlugin initEmbedCardWithId: <Tag>];

// you can add it in a UIStackView (recommended)
UIStackView *stackView = [[UIStackView alloc] init];
[stackView addArrangedSubview:embedCard];

// add your other existing views if any
[stackView addArrangedSubview:existingView1];
.
.

// if you want to add it in a UIView
UIView *sampleView = [[UIView alloc] init];
[sampleView addSubview:embedCard];

// add constraints (optional)
embedCard.translatesAutoresizingMaskIntoConstraints = NO;

[NSLayoutConstraint activateConstraints:@[
    [embedCard.topAnchor constraintEqualToAnchor:sampleView.topAnchor],
    [embedCard.leadingAnchor constraintEqualToAnchor:sampleView.leadingAnchor],
    [embedCard.bottomAnchor constraintEqualToAnchor:sampleView.bottomAnchor],
    [embedCard.trailingAnchor constraintEqualToAnchor:sampleView.trailingAnchor]
]];

Rename <Tag> to any unique ID (any positive Integer). Ensure that you keep the ID unique across different IDs and across different Embed Card instances.

Story Slot

Note

For using Apxor Stories the versions of the following plugins should be greater than or equal the ones mentioned below

Core: 2.10.26

RTA: 1.09.26

CE: 1.05.16

WYSIWYG: 1.02.67

In all areas of the app where you may want to show an in-line widget, insert the following code in the view controller:

// Swift

let StoryWidget = APXRTAPlugin.initStories(withId: <Tag>)!

// you can add it in a UIStackView (recommended)
let stackView = UIStackView()
stackView.addArrangedSubview(StoryWidget)

// add your other existing views if any
stackView.addArrangedSubview(existingView1)
.
.

// if you want to add it in a UIView
let sampleView = UIView()
sampleView.addSubview(StoryWidget)

// add constraints (optional)
StoryWidget.translatesAutoresizingMaskIntoConstraints = false

StoryWidget.topAnchor.constraint(equalTo: sampleView.topAnchor).isActive = true
StoryWidget.leadingAnchor.constraint(equalTo: sampleView.leadingAnchor).isActive = true
StoryWidget.bottomAnchor.constraint(equalTo: sampleView.bottomAnchor).isActive = true
StoryWidget.trailingAnchor.constraint(equalTo: sampleView.trailingAnchor).isActive = true
// Objective-C

APXStoryGroup *storyWidget = [APXRTAPlugin initStoriesWithId:<Tag>];

// you can add it in a UIStackView (recommended)
UIStackView *stackView = [[UIStackView alloc] init];
[stackView addArrangedSubview:storyWidget];

// add your other existing views if any
[stackView addArrangedSubview:existingView1];
.
.

// if you want to add it in a UIView
UIView *sampleView = [[UIView alloc] init];
[sampleView addSubview:storyWidget];

// add constraints (optional)
storyWidget.translatesAutoresizingMaskIntoConstraints = NO;

[NSLayoutConstraint activateConstraints:@[
    [storyWidget.topAnchor constraintEqualToAnchor:sampleView.topAnchor],
    [storyWidget.leadingAnchor constraintEqualToAnchor:sampleView.leadingAnchor],
    [storyWidget.bottomAnchor constraintEqualToAnchor:sampleView.bottomAnchor],
    [storyWidget.trailingAnchor constraintEqualToAnchor:sampleView.trailingAnchor]
]];

Rename <Tag> to any unique ID (any positive Integer). Ensure that you keep the ID unique across different IDs and across different Stories instances.

Ensuring Apxor SDK is initialized successfully

  • Lookout for the following log

Add-Ons

Now that you have completed the basic integration, you can proceed to set up event triggers, capture data for targeting, add slots for embed cards and stories, and personalize messaging. Include the following sections as needed.

Initializing the SDK

To start tracking with the Apxor iOS SDK, you must first initialize it. To initialize the SDK,

// ObjC
[ApxorSDK initializeApxorSDK];
// Swift
ApxorSDK.initializeApxorSDK()

Identifying the Users

ApxorSDK uses Identifier for Advertisers (IFA) to uniquely identify users. In cases where IFA is not available, we use Identifier for Vendors (IFV) for the same. Apart from this you can log a custom user identifier that you use to uniquely identify users in your app.

This identifier would be very instrumental specially when exporting data of a certain campaign or survey to your analytics system to create a cohort and measure the results of the campaign.

Similarly, when you are importing data to Apxor from your system that your marketing / product / data science team has identified and want to run campaigns specifically to them the custom user identifier will serve as the bridge to communicate between your systems and Apxor effectively.

Here is how you can set your user identifier for Apxor to recognise your users :

// ObjC
[ApxorSDK setUserIdentifier:@"1729"];
// Swift
ApxorSDK.setUserIdentifier("CustomUserIdentifier")

The product/marketing or the growth team lists out the use cases with an idea of when to launch and to whom to launch. To do this we need to capture data in the form of events. Let us consider the following use case as an example :

In the above scenario, we want to trigger the campaign for users who have spent 'x' seconds and haven't tapped on a product. To understand that if the user has tapped the product we should log an event along with its attributes as follows to capture data:

Similarly if you want to send promotions to users who have viewed at least five products of the category shoes in the last three days or you want to measure how many people added an item to a cart from the campaign as a goal all this information is captured in the form of events.

These types of events are classified as app events - the data that is transferred to the servers at Apxor where you can segment users based on historic behavior or measure your goals as specified above.

To track an event with the event name and properties.

// ObjC
NSDictionary *info = [[NSDictionary alloc] init];
[info setValue:@"Select Language" forKey:@"event_type"];
[info setValue:@"Valyrian" forKey:@"event_type"];
[ApxorSDK logAppEventForEvent:@"LANG_SELECT" withInfo:info];
// Swift
let eventDict = ["event_type":"Select Language", "event_type":"Valyrian"] as [String : AnyObject]
ApxorSDK.logAppEvent(withName: "EventName", info: eventDict)

User Attributes

We can personalize the messaging copy in the experiences we build for the user or target based on his persona using information that is centric to individual users. Let us consider the following example where we know the user is an English with Gold membership.

This information helps to tailor content in English to that specific user and gives us the flexibility to different messaging to different membership tiers. This is how the information captured here is used for segmenting.

Similarly capturing attributes like Name can help to personalize your message copy where it reads Hi {username} can't find your product? where the username is replaced by the attribute value of the property from the nudges dashboard along with providing meaningful defaults in their absence.

This is how you log user information to Apxor :

// ObjC
NSDictionary *info = [[NSDictionary alloc] init];
[info setValue:@"spock@vulcan.com" forKey:@"email"];
[ApxorSDK setUserCustomInfo:info];
// Swift
let userInfo = ["email": "spock@vulcan.com"] as [String : AnyObject]
ApxorSDK.setUserCustomInfo(userInfo)

Session Attributes

A Session can be simply defined as a user journey as he opens the app, until he closes the app. There can be various pieces of information that can be very impactful when accumulated in a session. For example, location in a session can be useful to know precisely where the user is utilizing the app most.

To add session attributes that are specific to a session,

// ObjC
NSDictionary *info = [[NSDictionary alloc] init];
[info setValue:@"In a galaxy far far away" forKey:@"location"];
[ApxorSDK setSessionCustomInfo:info];
// Swift
let userInfo = ["location": "In a galaxy far far away"] as [String : AnyObject]
ApxorSDK.setSessionCustomInfo(userInfo)

Client Events

In the below scenario, let's assume you want to launch a survey when the soft back button is pressed asking the user for product feedback. In this, we don't need to capture the data of how many people pressed the back button which is useless and it bloats your event storage as it is a high-frequency event which increases your cost unnecessarily. This data point doesn't potentially answer any of your product questions and hence there is no ROI in storing data from this event.

So for such scenarios where we need the behavioral data to launch a campaign or to collect feedback, which doesn't provide ROI on storing for measuring goals, answering your product questions or segmenting your target audience, we log these events as Client Events which involves zero transfer of data and is used only to set up your triggers on behavioral information from the user.

Events that are logged to reside on the client application are called client events, the data captured is not transferred to Apxor.

These are typically logged to capture behavioral observations and interactions to nudge a user.

Example:

Soft back button, user reaching end of page, etc.

// ObjC
NSDictionary *info = [[NSDictionary alloc] init];
[info setValue:@"com.example.app.SettingsViewController" forKey:@"Screen"];
[ApxorSDK logClientEventWithName:@"SoftBackPressed" info:info];
// Swift
let eventDict = ["Screen":"com.example.app.SettingsViewController"] as [String : AnyObject]
ApxorSDK.logClientEvent(withName: "SoftBackPressed", info: eventDict)

Track Screens

In the scenario discussed in this guide, how will we know if the user has spent thirty seconds on the home screen and did not click on the product? For this reason, it is important to use track the screens to set them up as triggers and also to capture the time spent on the screens.

ApxorSDK automatically captures screens and their names for most view controllers. In some cases where TabBarController is used, the OS won't be providing any notifications to capture the screens automatically.

For these cases, we encourage you to log screen events using the following API. Make sure to log the API inside the viewWillAppear function.

// ObjC
- (void)viewWillAppear:(BOOL)animated {

    [ApxorSDK logScreenWithName:@"FirstViewController"];
    /*
      ... your code here ...
     */
}
// Swift
override func viewWillAppear(animated: Bool) {

    ApxorSDK.logScreenWithName("FirstViewController")
    /*
      ... your code here ...
    */
}

Reporting Custom Errors

Custom errors describe situations like LOGIN_FAILED, NETWORK_CALL_FAILED and are to be treated differently compared to app events. So these are treated as errors and are shown on the issues page to let you know their impact.

A custom error takes the exception itself and some context (what? OR which?) to make it easy for you to identify. To report a custom error,

// ObjC
NSException* myException = [NSException
                            exceptionWithName:@"FileNotFoundException"
                            reason:@"File Not Found on System"
                            userInfo:nil];
[ApxorSDK reportCustomError:myException withContext:@"customException"];
// Swift
let errorInfo = ["reason": "File Not Found on System"]  as [String : AnyObject]
var customError = NSError(domain:"", code:httpResponse.statusCode, userInfo:nil)
ApxorSDK.reportCustomError(customError, withInfo: errorInfo)

Custom Fonts

ApxorSDK supports two types of fonts namely, .ttf(TrueType fonts) and .otf(OpenType fonts). Custom fonts can be used in ApxorSDK's real time actions in two simple steps.

Adding custom fonts to your application

  • Fonts of your choice and selection are to be added in the Project's Supporting files section

  • Edit the Info.plist file to add the font names in the Fonts provided by application

  • Ensure the fonts are available in, Build phases --> Copy Bundle resources

While configuring the campaigns in the dashboard

  • Enable custom fonts

  • Enter the same exact font file name along with the extenstion (.ttf or .otf)

You're all set! 🎉

Note

Font properties like Bold, Italic cannot be used in the dashboard for custom fonts. The exact font file with those properties has to be added in your application.

Handle custom redirection using Key-Value pairs

If your app wants to redirect users based on simple key-value pairs instead using Deeplink URLs or Activity, you can follow below approach

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

  // Your code here
  // ...
  NotificationCenter.default.addObserver(self, selector: #selector(self.onRedirectionClicked(notification:)), name: Notification.Name("APXRedirectionNotification"), object: nil)
}

@objc func onRedirectionClicked(notification: NSNotification) {
  if let kvPairs = notification.userInfo!["info"] {
      print(kvPairs)
      // ...
      // use kvPairs 
      // ...
  }
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  // Your code here
  // ...
  [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onRedirectionClicked:) name:@"APXRedirectionNotification" object:nil];
}

- (void) onRedirectionClicked:(NSNotification *) notification
{
  NSLog(@"kvPairs: %@", notification.userInfo["info"]);
  // ...
  // use kvPairs 
  // ...
}

To get Apxor Device Identifier

Apxor SDK maintains a unique ID for every user. To get the Apxor Device ID,

NSString *deviceId = [ApxorSDK getDeviceID];

Note

If the deviceID is nil, please retry after a few seconds.

Log Events inside WebView

It is suggested that you log events inside your WebView once the page is completely rendered using Apxor Javascript Interface methods. Based on these events, you can configure Tooltips.

  • Methods exposed from Apxor Javascript Interface

    window.webkit.messageHandlers.logAppEvent.postMessage({"name": "...", "info": "..."});
    window.webkit.messageHandlers.logClientEvent.postMessage({"name": "...", "info": "..."});

    Note

    Make sure the keys of the dictionary in postMessage are "name" and "info", do not change them.

  • Examples for logging App Event

    Example:

    Log an event on page load event.

    ...
    <head>
      ...
      <script>
        function logApxorEvent(eventName, attributes) {
          if (window.webkit) {
            window.webkit.messageHandlers.logAppEvent.postMessage({"name": eventName, "info": attributes});
          }
        }
      </script>
    </head>
    <body onload="logApxorEvent('PageLoaded')">
      ...
    </body>

    Example (React based web pages):

    Log an event on componentDidMount.

    componentDidMount() {
        if (window.webkit) {
            window.webkit.messageHandlers.logAppEvent.postMessage({"name": 'LoginPageLoaded'});
        }
    }

Actions in WebView

Many native applications feature WebViews to display descriptive content and much more. Apxor iOS SDK provides a way to show real-time actions inside that WebView to make the most of it.

Following are the steps in order to show real-time actions in your WebView.

  • Add a tag to the webview (which is to be later provided in the dashboard) as shown.

    // ObjC
    [self.webview setTag:007];

    // Swift
    webview.tag = 007;
  • You have to init the APXWKScriptHandler and call registerEventsAndScripts method to make sure any the calls made in the webview are taken care by the native SDK. It's as follows,

    • Add the following in the bridging header file.

    #import "APXRTAPlugin/APXWKScriptHandler.h"
    • Now, add the following to the init method of your webview

    let apxHandler: APXWKScriptHandler = APXWKScriptHandler.init(handlerFor: webView)
    apxHandler.registerEventsAndScripts()
  • Here's how to do the same thing in objective-C.

    • Make sure there's a proper WKUserContentController set to your WkWebView, if not please init it and use that config to initialise your WKWebView.

    WKUserContentController *controller = [[WKUserContentController alloc] init];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.userContentController = controller;
    #import "APXRTAPlugin/APXWKScriptHandler.h"
    ...
    // add apxor's script handler
    APXWKScriptHandler *scriptHandler = [[APXWKScriptHandler alloc] initWithHandlerForWebView:_webView];
    [scriptHandler registerEventsAndScripts];
  • Also, make sure there’s an id for the web element that you want to show tooltip on.

  • In the above example, the element button has an attribute id = change_button, which will used to identify that particular element.

Dynamic Script Text in actions

A new capability of writing dynamic text in actions (Tooltips & InApps) had been introduced in latest release of Apxor SDK plugins.

You can write a script (a new language that Apxor is created which somewhat looks like Javascript) instead of plain text to substitue user and session properties that you have already logged to Apxor SDK or you can substitute a text element from your application or hidden text that you set it as keyed tag (apx_view_tag).

The Apxor Language

The Apxor language looks similar to Javascript with some modifications.

We assume every dynamic param that you want to substitute in a text is a pre-defined variable that you can create upfront in the Script dialog that Apxor Dashboard provides to you.

We support following operators and keywords as part of our language specification

Unary Operators

! (Negation)

Logical Operators

&& (Logical AND)

|| (Logical OR)

Mathematical Operators

+ (Arithmetic Addition)

- (Arithmetic Subtraction)

* (Arithmetic Multiplication)

/ (Arithmetic Division)

% (Arithmetic Modulo)

Comparison Operators

< (Less than)

<= (Less than or Equals)

> (Greater than)

>= (Greater than or Equals)

== (Equality)

!= (Not Equality)

contains (Checks if a string contains another string)

Keywords

httpGet, onSuccess, onError will be used to make a HTTP GET API call

format will be used to format a string

if, else will be used to write conditional evaluation

true, false boolean keywords

toInt will be helful to convert double/float values to integer

Examples

Note:

Assume the following variables are defined

  • UserName (User Property)

  • RewardPoints (User Property)

  • IsSubscribed (User Property)

  • Subscribed (API JSON response parameter user.is_subscribed)

  • Simple formatting of string

format(
  "Hello {}. We are exicted to give you {} reward points. You can see these points in Rewards section",
  UserName,
  toInt(RewardPoints)
);
  • Conditional Dynamic Text

if (!IsSubscribed && RewardPoints < 500) {
  format(
    "Hello {}, you are just {} points away to get free subscription",
    UserName,
    500 - RewardPoints
  );
} else {
  format("Hello {}, You are already subscribed", UserName);
}
  • API call

httpGet(format("https://your-server.com/your-api?userName={}", UserName))
  .onSuccess(() => {
    if (SubScribed) {
      format("Hello {}, you are already subscribed", UserName);
    } else {
      format("Hello {}, you are not subscribed yet", UserName);
    }
  })
  .onError(() => format("Something went wrong. Try again later"));

Install CocoaPods, if you don't already have it. CocoaPods is a dependency manager for Swift and Objective-C Cocoa projects. It has over 95 thousand libraries and is used in over 3 million apps. CocoaPods can help you scale your projects elegantly. If you don't want to use CocoaPods, you can install ApxorSDK .

to log user properties, events and event properties.

Setting up campaign triggers, capturing data for targetting and goal tracking

App Events

Personalizing and targeting by user persona

If you don't already have a bridging header,

Yeah! You are ready to create your first or

manually
Click here for guide
​
​
​
checkout how to create a bridging header.
Campaign
Survey
Read more on how to fetch the application identifier from Apxor dashboard
(Know more about bundle ids here)
Read more on how you can setup here
Check here for the latest release notes