# iOS SDK (Swift UI)

#### 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\
  \
  ([Read more on how to fetch the application identifier from Apxor dashboard](https://guides.apxor.com/getting-started-with-apxor/adding-a-new-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.\
  \
  [(Know more about bundle ids here)](https://developer.apple.com/documentation/appstoreconnectapi/bundle-ids)
* **The list of events** to setup triggers and track goals, user properties that allows to personalize messages and to target better.\
  \
  ([Read more on how you can setup here](https://guides.apxor.com/getting-started-with-apxor/api-guides/ios))

{% hint style="info" %}
**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](https://guides.apxor.com/getting-started-with-apxor/sdk/broken-reference) to migrate all the events that you are sending to one of the supported third parties as listed in the guide.
{% endhint %}

## Getting started with Apxor iOS

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

<table><thead><tr><th width="206.33333333333331">Plugin Name</th><th width="253">Description</th><th>Example</th></tr></thead><tbody><tr><td>Apxor-Core</td><td>The Core Plugin is responsible for the basic event tracking</td><td>How many of my users have clicked on the cart icon after showing them a nudge Sample Event : 'ViewCart'</td></tr><tr><td>APXSurveyPlugin</td><td>This Plugin helps you create contextual surveys to capture your users' feedback, ratings, etc.</td><td>An NPS survey that would ask the user to rate the app experience on a scale of 1-10.</td></tr><tr><td>APXRTAPlugin</td><td>This Plugin helps you create real time actions.</td><td>Show a tooltip on the cart icon with messaging "Tap here to view items"</td></tr><tr><td>APXWYSIWYGPlugin</td><td>The WYSIWYG Plugin allows you to preview your configured actions onto your device in real time</td><td>Casting your mobile screen to the dashboard and selecting the hamburger icon</td></tr><tr><td>APXPushPlugin</td><td>The Push Plugin allows you to track uninstalls and real-time serve/pause the nudges, while the app is opened</td><td>Show a campaign to users who land on the home screen and add an item to the cart.</td></tr></tbody></table>

[Check here for the latest release notes](https://guides.apxor.com/release-notes#ios).

## Adding Apxor SDK to your project

* 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 [manually](https://guides.apxor.com/getting-started-with-apxor/sdk/broken-reference).
* 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.43'
pod 'Apxor-CE', '1.05.31'
pod 'Apxor-Push', '1.01.04'
pod 'Apxor-RTA', '1.09.48'
pod 'Apxor-WYSIWYG', '1.02.74'
pod 'Apxor-Survey', '1.04.23'
pod 'Apxor-SwiftUI', '1.01.01'
```

## 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.

<figure><img src="https://300211688-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQuYbJ9bg7CFtrBaVp9pB%2Fuploads%2FGe4QC4GoIm6EL7U1kQ4X%2Finfo-plist.png?alt=media&#x26;token=acb558d4-5106-4a0b-809b-b0b9bb750d7f" alt=""><figcaption></figcaption></figure>

* 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.

<figure><img src="https://300211688-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQuYbJ9bg7CFtrBaVp9pB%2Fuploads%2FGe4QC4GoIm6EL7U1kQ4X%2Finfo-plist.png?alt=media&#x26;token=acb558d4-5106-4a0b-809b-b0b9bb750d7f" alt=""><figcaption></figcaption></figure>

* 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>
```

{% hint style="info" %}
**Note**

To get your app ID, please email us at <mark style="color:blue;">**<contact@apxor.com>**</mark>
{% endhint %}

### Initialize Apxor SwiftUI SDK

```swift
import APXSwiftUIPlugin

ContentView()
    .onAppear {
    initializeApxorSwiftUISDK(status: true)
}

```

{% hint style="info" %}
**Note**

To get your app ID, please email us at <mark style="color:blue;">**<contact@apxor.com>**</mark>
{% endhint %}

## Configuring IDs for View (Mandatory for inlines)

```swift
import APXSwiftUIPlugin

Text("Hello, world!")
    .APXLabel(viewId: "text", screen: "ScreenName")
```

## 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.

<figure><img src="https://300211688-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQuYbJ9bg7CFtrBaVp9pB%2Fuploads%2FOUSQnitryUH0s7X1U1fE%2Furl_scheme.png?alt=media&#x26;token=844c999c-be85-4db5-8c42-74bd352c70de" alt=""><figcaption></figcaption></figure>

{% hint style="info" %}
**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.**
{% endhint %}

### Handling the deep link

```swift
@main
struct YourApplication: App {
    var body: some Scene {
        return WindowGroup {
            TabView {
                YourView().tabItem {
                    Image("Icon")
                    Text("Text")
                }
            }
            .onOpenURL { urlString in
                if(urlString.absoluteString.contains("add-test-device")) {
                    ApxorSDK .handleDeeplink(urlString)
                }
            }
        }
    }
```

## Log Screens using the following api in Swift UI

```swift
ApxorSDK.logScreen(withName: "screen_name");
```

## 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.

```swift
import APXPushPlugin

let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
print("Device Token: \(token)")
APXPushPlugin.setPushDeviceToken(token)
```

```objectivec
[APXPushPlugin setPushDeviceToken:token];
```

* The token can be passed in either the **`NSData`** or **`NSString`** format

<figure><img src="https://300211688-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQuYbJ9bg7CFtrBaVp9pB%2Fuploads%2FHbFbnu8Xz2wc0U9f78iG%2Fconf_push_notif_3.png?alt=media&#x26;token=43b5e33b-c1b9-4925-9a3e-34c66e3ad4d0" alt=""><figcaption></figcaption></figure>

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

```swift
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()
    }
  }
}
```

## Ensuring Apxor SDK is initialized successfully

* Lookout for the following log

<figure><img src="https://300211688-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQuYbJ9bg7CFtrBaVp9pB%2Fuploads%2FCBs7zfjJEVBXzo2EMT6k%2Fensure_last.png?alt=media&#x26;token=42157b63-0717-4e1e-8de0-28a8b634abf1" alt=""><figcaption></figcaption></figure>

<figure><img src="https://300211688-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FQuYbJ9bg7CFtrBaVp9pB%2Fuploads%2Fw7AqZIHgoaKvu48JKoxj%2Fnote_last.png?alt=media&#x26;token=19c41baa-2703-460d-b639-d9089ca34b8e" alt=""><figcaption></figcaption></figure>

[Click here for guide](https://guides.apxor.com/getting-started-with-apxor/api-guides/ios) to log user properties, events and event properties.
