# iOS SDK

# Intempt iOS SDK API Documentation

## Overview
The iOS SDK enables you to track user interactions within your iOS app and manage its configuration via the Intempt console.

The initialized iOS SDK automatically collects the following events with data-rich attributes:

### Auto-Tracked Events

| Event              | Definition                                                                                                                     |
| ------------------ | ------------------------------------------------------------------------------------------------------------------------------- |
| **Touch**          | Recorded when a user taps or touches a UI control, such as buttons, sliders, or any interactive elements.                      |
| **View Screen**    | Captured every time a user views a screen within the app. Useful for tracking navigation and screen engagement.                 |
| **Leave Screen**   | Logged when a user exits a screen. Helps understand user flows and potential interface issues.                                 |
| **Action**         | Triggered by an interaction like submitting a form or clicking a link. Useful for identifying effective CTAs.                  |
| **App Install/Upgrade** | Tracks app installations or upgrades with version and build details.                                                        |
| **Start Session**  | Logs the start of a new user session.                                                                                          |
| **End Session**    | Recorded after 5 minutes of inactivity, useful for session length analysis.                                                     |

Following this guide, you can also track custom events and perform personalization campaigns and A/B experiments.

---

## Requirements
- iOS 13.0+
- Xcode 11.0 or later

---

# Installation

## Create a Source
1. Go to *Integrations → Sources*.
2. Click **Create Source**.
3. Choose the **iOS** option.
4. Copy the snippet provided — you'll need it for SDK initialization.

---

## Create the API Key
Refer to the **API Keys** section to generate a unique API key for authenticating the SDK.

---

# Initialize the SDK

## Integration using Swift Package Manager
Intempt fully supports Swift Package Manager.

1. Open your `.xcodeproj`.
2. Navigate to **File → Add Packages…**
3. Paste the URL:

```

[https://github.com/intempt/intempt-intemptios](https://github.com/intempt/intempt-intemptios)

````

4. Choose the `master` branch.

---

## Integration as a Manual Framework

1. Download the SDK repository as a ZIP file.
2. Locate `Intempt.xcframework`.
3. Copy it into your project directory.
4. Drag & drop `Intempt.xcframework` into your iOS app in Xcode.
5. Set **Embed & Sign**:

- Go to **Target → Build Phases**
- Expand **Embed Frameworks**
- Add `Intempt.xcframework`
- Go to **Target → General → Frameworks, Libraries, and Embedded Content**
- Ensure **Embed & Sign** is selected.

After these steps, the project should compile without errors.

---

# Initialization — Swift

> Works with Xcode 11.3+

## SceneDelegate.swift

```swift
import Intempt

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    guard let _ = (scene as? UIWindowScene) else { return }

    let intemptConfig = IntemptConfig(
        queueEnabled: true,
        withItemsInQueue: 7,
        withTimeBuffer: 15,
        withInitialDelay: 0.3,
        withInputTextCaptureDisabled: false
    )

    Intempt.initialize(<orgName>, projectName: <projectName>, sourceId: <sourceId>, apiKey: <apiKey>, intemptConfig: intemptConfig) { (status, result, error) in
        if (status) {
            if let dictResult = result as? [String: Any] {
                print(dictResult)
            }
        } else {
            if let error = error {
                print(error.localizedDescription)
            }
        }
    }
}
````

## ViewController.swift

```swift
override func viewDidLoad() {
    super.viewDidLoad()

    let intemptConfig = IntemptConfig(
        queueEnabled: true,
        withItemsInQueue: 7,
        withTimeBuffer: 15,
        withInitialDelay: 0.3,
        withInputTextCaptureDisabled: false
    )

    Intempt.initialize(<orgName>, projectName: <projectName>, sourceId: <sourceId>, apiKey: <apiKey>, intemptConfig: intemptConfig) { (status, result, error) in
        if (status) {
            if let dictResult = result as? [String: Any] {
                print(dictResult)
            }
        } else {
            if let error = error {
                print(error.localizedDescription)
            }
        }
    }
}
```

---

# Initialization — Objective-C

## AppDelegate.m (Xcode 11.3+)

```objectivec
@import Intempt;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    IntemptConfig *intemptConfig = [[IntemptConfig alloc]
        initWithQueueEnabled:YES
        withItemsInQueue:7
        withTimeBuffer:15
        withInitialDelay:0.3
        withInputTextCaptureDisabled:NO
    ];

    [Intempt initialize:<orgName>
            projectName:<projectName>
              sourceId:<sourceId>
                apiKey:<apiKey>
         intemptConfig:intemptConfig
         onCompletion:^(BOOL status, id result, NSError *error) {
    }];

    return YES;
}
```

## ViewController.m

```objectivec
@import Intempt;

- (void)viewDidLoad {
    [super viewDidLoad];

    IntemptConfig *intemptConfig = [[IntemptConfig alloc]
        initWithQueueEnabled:YES
        withItemsInQueue:7
        withTimeBuffer:15
        withInitialDelay:0.3
        withInputTextCaptureDisabled:NO
    ];

    [Intempt initialize:<orgName>
            projectName:<projectName>
              sourceId:<sourceId>
                apiKey:<apiKey>
         intemptConfig:intemptConfig
         onCompletion:^(BOOL status, id result, NSError *error) {
    }];
}
```

---

# Authorize SDK

Copy the following from the Intempt console:

* Source ID
* Project ID
* Organization ID
* API Key

Use them in your initialization parameters.

---

# Supported Event Types

## Auto-Tracked Events

Touch
View Screen
Leave Screen
Action
App Install/Upgrade
Start Session
End Session

## Custom Events

Custom events are actions you define inside your code.

Once tracked, custom events appear automatically in the **Events** list of the Intempt console.

---

# SDK Methods

## IntemptConfig Parameters

| Parameter                  | Type         | Purpose                                                     |
| -------------------------- | ------------ | ----------------------------------------------------------- |
| queueEnabled               | BOOL         | Enables batching events. Default: YES                       |
| itemsInQueue               | Int          | Number of events needed before a batch is sent. Default: 5  |
| timeBuffer                 | TimeInterval | Interval in seconds to send events periodically. Default: 5 |
| isInputTextCaptureDisabled | BOOL         | Prevents capturing text inputs. Default: NO                 |
| initialDelay               | TimeInterval | Delay before sending events. Default: 0.2                   |

---

## Track

```swift
let objData:[String:Any] = [
    "flightId" : 1,
    "bookingDate" : "2024-01-29",
    "bookingId": 2,
    "bookingStatus" : "booked"
]

Intempt.track("flight-booking", data: objData) { (status, result, error) in
    if(status) {
        if let dictResult = result as? [String: Any] {
            print(dictResult)
        }
    } else {
        if let error = error {
            print(error.localizedDescription)
        }
    }
}
```

---

## Record

```swift
let objData:[String:Any] = [
    "flightId" : 1,
    "bookingDate" : "2024-01-29",
    "bookingId": 2,
    "bookingStatus" : "booked"
]

let accountAttributes:[String:Any] = [
    "mtuCount" : "1000+"
]

let userAttributes:[String:Any] = [
    "city" : "New York",
    "country" : "USA"
]

Intempt.record(
    "flight-booking",
    userId: "xyz@intempt.com",
    accountId: "intempt.com",
    data: objData,
    accountAttributes: accountAttributes,
    userAttributes: userAttributes
) { (status, result, error) in }
```

---

## identify()

```swift
Intempt.identify("xyz@intempt.com") { (status, result, error) in }
```

### Identify with attributes

```swift
let userAttributes:[String:Any] = [
    "city" : "New York",
    "country" : "USA"
]

Intempt.identify(
    "xyz@intempt.com",
    eventTitle: "CustomIdentify",
    userAttributes: userAttributes
) { (status, result, error) in }
```

---

## group()

```swift
Intempt.group("intempt.com") { (status, result, error) in }
```

### Group with attributes

```swift
let userAttributes:[String:Any] = [
    "name" : "John",
    "country" : "USA"
]

Intempt.group(
    "CustomGroupIdentify",
    accountId: "intempt.com",
    userAttributes: userAttributes
) { (status, result, error) in }
```

---

## Consent

### Accept

```swift
Intempt.consents(
    IntemptConsentAction.Accept.rawValue,
    consentsExpirationTime: "Unlimited",
    email: "xyz@intempt.com",
    message: "Yes, email me offers."
) { (status, result, error) in }
```

### Reject

```swift
Intempt.consents(IntemptConsentAction.Reject.rawValue) { (status, result, error) in }
```

### Category Consent

```swift
Intempt.consent(
    IntemptConsentAction.Accept.rawValue,
    consentsExpirationTime: "Unlimited",
    category: "News",
    email: "xyz@intempt.com",
    message: "Yes, email me offers."
) { (status, result, error) in }
```

---

# Alias

```swift
Intempt.alias("xyz@intempt.com", anotherUserId: "abc@intempt.com") { (status, result, error) in }
```

---

# Product Events

### productView

```swift
Intempt.productView(productId: "123") { (status, result, error) in }
```

### productAdd

```swift
Intempt.productAdd(productId: "123", quantity:1) { (status, result, error) in }
```

### productOrdered

```swift
var productsOrdered = [[String: Any]]()

for item in CartController.shared.items {
    productsOrdered.append(["productId": item.productId, "quantity": item.quantity])
}

Intempt.productOrdered(params: productsOrdered) { (status, result, error) in }
```

---

# Utility Methods

### isUserOptIn

```swift
Intempt.isUserOptIn()
```

### logout

```swift
Intempt.logout()
```

### getProfileId

```swift
let profileId = Intempt.getProfileId()
```

### getSessionId

```swift
let sessionId = Intempt.getSesssionId()
```

### disableTextInput

```swift
Intempt.disableTextInput(true)
```

### optOut

```swift
Intempt.optOut()
```

### optIn

```swift
Intempt.optIn()
```

### enableLogging

```swift
Intempt.enableLogging()
```

### disableLogging

```swift
Intempt.disableLogging()
```

### validateTrackingSession

```swift
Intempt.validateTrackingSession()
```

### endTrackingSession

```swift
Intempt.endTrackingSession()
```

### startTrackingSession

```swift
Intempt.startTrackingSession()
```

---

# Experiments & Personalization

## chooseExperiments (byNames)

```swift
Intempt.chooseExperiments(
    byNames: ["Special_Discount"],
    productId: "2369423736890"
) { (status, result, error) in }
```

## chooseExperiments (byGroups)

```swift
Intempt.chooseExperiments(
    byGroups: ["Banners"],
    productId: "2369423736890"
) { (status, result, error) in }
```

---

# choosePersonalizations (byNames)

```swift
Intempt.choosePersonalizations(
    byNames: ["home_page_pop-up"],
    productId: "2369423736890"
) { (status, result, error) in }
```

# choosePersonalizations (byGroups)

```swift
Intempt.choosePersonalizations(
    byGroups: ["banner"],
    productId: "2369423736890"
) { (status, result, error) in }
```

---

# Recommendation API

```swift
Intempt.recommendation(
    "9",
    fields: ["id", "price", "title"],
    quantity: 4,
    productId: productId
) { (status, result, error) in }
```

---

# Troubleshooting

## Framework built for unsupported architectures

Set:
Target → Build Settings → Validate Workspace = NO
Toggle YES → NO if needed.

## App Store architecture errors

Add a **Run Script Phase** and include the provided lipo-cleaning script.

## dyld: Library not loaded

Ensure:
`Intempt.xcframework` = **Embed & Sign**

## "Intempt no such module"

Delete the framework, clean DerivedData, re-add `Intempt.xcframework`.

## No data visible

iOS SDK batches events periodically — allow a few seconds.

## Events taking too long to send

Check:

* `timeBuffer`
* `itemsInQueue`

## Field Type Validation

Ensure event fields match the schema types.

Example:
String expected:

Accepted:
const event = { name: "John Doe" }

Rejected:
const event = { name: { first: "John", last: "Doe" } }

Adding new fields is supported — existing fields must remain same type.


