> ## Documentation Index
> Fetch the complete documentation index at: https://docs.knotapi.com/llms.txt
> Use this file to discover all available pages before exploring further.

# iOS

> Integrate the Knot iOS SDK into your iOS application to enable merchant account linking.

## Overview

<Tip>
  **SDK Updates**\
  New versions of the SDK are released frequently, not only to add new features and address issues in the SDK, but also to continuously improve the conversion of merchant login flows. As a result, it is strongly recommended that you frequently update your SDK version across any platforms where you invoke the SDK.
</Tip>

The Knot Link SDK provides a seamless way for end users to link their merchant accounts to your iOS app, serving as the foundation for Knot's merchant connectivity platform. It is a client-side integration, consisting of initializing & configuring the SDK and handling events.

## Installation

The Knot SDK can be installed using **CocoaPods** or **Swift Package Manager (SPM)**.

### Using CocoaPods

<Steps>
  <Step title="Install CocoaPods">
    If you haven't already, install the latest version of CocoaPods.
  </Step>

  <Step title="Create a Podfile">
    If you don't have an existing Podfile, run the following command to create one:

    ```ruby theme={"system"}
    pod init
    ```
  </Step>

  <Step title="Add to your Podfile">
    Add the below line to your Podfile in your iOS project directory:

    ```
    pod 'KnotAPI'
    ```
  </Step>
</Steps>

### Using Swift Package Manager (SPM)

<Note>
  To install the Knot SDK using Swift Package Manager, ensure you're using Swift version 5.3 or later.
</Note>

<Steps>
  <Step title="Go to File, Add Packages">
    In your Xcode project, go to File, Add Packages.
  </Step>

  <Step title="Enter Knot package URL">
    In the top right corner of the dialog box, you'll see a search bar. Enter the Knot package URL: [https://github.com/millionscard/knot-api-ios](https://github.com/millionscard/knot-api-ios). From the results, choose the `knot-api-ios` package.
  </Step>

  <Step title="Decide on your Dependency Rule">
    It is recommended to opt for Up to Next Major Version. Choose the project you want to integrate with KnotAPI and click on Add Package.
  </Step>

  <Step title="Confirm package dependency">
    Confirm that the KnotAPI Swift package was added as a package dependency to your project successfully.
  </Step>
</Steps>

## Initialization

Your backend will create a session by calling [Create Session](/api-reference/sessions/create-session) and provide it to your frontend. To start a Knot session, you must first configure the session with a `KnotConfiguration` class. The configuration allows you to set the environment, entry point, and other user experience configurations.

<Note>
  It's expected that your integration with Knot will retrieve and pass a new session into the SDK on each initialization.
</Note>

### Configure the session

The `KnotConfiguration` and `CustomerConfiguration` classes are used to initialize the SDK with specific parameters.

#### `KnotConfiguration`

| Name          | Type               | Description                                                                                                                                                                                                                                    |
| :------------ | :----------------- | :--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| sessionId     | String             | The session created by calling `/session/create` in your backend.                                                                                                                                                                              |
| clientId      | String             | Your organization's client ID. Note that this varies between `development` and `production` environments.                                                                                                                                      |
| environment   | Environment        | The desired environment (`development` or `production`).                                                                                                                                                                                       |
| entryPoint    | String?            | **Optional.** The specific entry point from within your app where you are initializing the Knot SDK (e.g. `onboarding`).                                                                                                                       |
| merchantIds   | \[Int]?            | **Optional.** A list of merchant ID(s) to display. It is recommended to provide 0 or 1 merchant ID depending on your desired user experience.                                                                                                  |
| useCategories | Bool               | **Optional.** Whether to display merchant categories and therefore group merchants into categories for discoverability. Default: `true`.                                                                                                       |
| useSearch     | Bool               | **Optional.** Whether to display the search bar, enabling users to search for merchants. Default: `true`.                                                                                                                                      |
| metadata      | \[String: String]? | **Optional.** Custom key-value pairs to include in [webhook](/webhooks#session-metadata) payloads. Maximum 10 keys with string values up to 500 characters each.                                                                               |
| locale        | String?            | **Optional.** A [BCP-47](https://developer.mozilla.org/en-US/docs/Glossary/BCP_47_language_tag) language tag to set the locale for the SDK. Currently supported: `en-US`, `es-US`, `en-CA`, and `fr-CA`. If not provided, defaults to `en-US`. |
| product       | Product            | **Optional. Ignored in version 1.0.11+.** The Knot product the session will inherit the same as the type of session created (e.g. `card_switcher`, `transaction_link`).                                                                        |

#### `CustomerConfiguration`

<Warning>
  This class is entirely optional and infrequently used, typically only when you offer Knot for multiple, differently-named card programs in the same app. The Knot team will set pre-defined values of your choosing for each parameter that you can then subsequently pass into the SDK. Passing a value that is not pre-defined will result in an `onError` callback. To take advantage of this functionality, please contact the Knot team who will be happy to assist you.
</Warning>

| Name         | Type   | Description                                                                                                                                                                                                                                                                         |
| :----------- | :----- | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| cardName     | String | **Optional.** The differentiated display name for the card product, used inside the Knot SDK (e.g. `Debit Card`, `Credit Card`). This value will override the default value `card`.                                                                                                 |
| customerName | String | **Optional.** The differentiated display name for the company, used both as a standalone and prepended to the `cardName` (e.g. `Smart Bank`, `Payment Corp`). This value will override your default customer name value. Only recommended if you issue cards under multiple brands. |
| logoId       | String | **Optional.** The differentiated logo for the company. This value will override your default logo.                                                                                                                                                                                  |

See the following examples for how the parameters are used together in text inside the Knot SDK:

`"Your [customerName] [cardName | card] was added."`

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  let customerConfiguration = CustomerConfiguration(
      cardName: "Card Name",		    // Your cardName
      customerName: "Customer Name",  // Your customerName
      logoId: "LogoId"				// Your logoID
  )

  let config = KnotConfiguration(
      sessionId: "session_12345",     // Current session ID
      clientId: "client_67890",       // Your client ID
      environment: .production,       // 'development' | 'production'
      merchantIds: [52],              // Recommend 0 or 1 merchant IDs
      useCategories: true,            // Recommend true
      useSearch: true,                // Recommend true
      domainUrls: nil,                // Explicitly passing nil
      entryPoint: "onboarding",       // Defined by you
      metadata: [                     // Optional metadata for webhooks
          "reference_token": "your-token",
          "trace_id": "your-trace-id"
      ],
      customerConfiguration: customerConfiguration,
      locale: "es-US"                 // Optional BCP-47 language tag
  )
  ```

  ```Objective-C Objective-C icon=c theme={"system"}
  CustomerConfiguration *customerConfiguration = [[CustomerConfiguration alloc]
      initWithCardName:@"Card Name"
          customerName:@"Customer Name"
               logoId:@"LogoId"];

  NSDictionary *metadata = @{
      @"reference_token": @"your-token",
      @"trace_id": @"your-trace-id"
  };

  KnotConfiguration *config = [[KnotConfiguration alloc]
      initWithSessionId:@"session_12345"
               clientId:@"client_67890"
            environment:EnvironmentDevelopment   // enum case
             entryPoint:@"onboarding"
                product:ProductCard_switcher     // enum case
          useCategories:YES
              useSearch:YES
            merchantIds:@[@52]
               metadata:metadata
  customerConfiguration:customerConfiguration
                 locale:@"es-US"];              // Optional BCP-47 language tag
  ```
</CodeGroup>

### Open the session

To begin the flow, use the `open` method with a `KnotConfiguration` instance and an optional `KnotEventDelegate`.

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  Knot.open(configuration: myConfiguration, delegate: self)
  ```

  ```Objective-C Objective-C icon=c theme={"system"}
  [Knot openWithConfiguration:config delegate:self];
  ```
</CodeGroup>

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  let customerConfiguration = CustomerConfiguration(
      cardName: "Card Name",		   
      customerName: "Customer Name",
      logoId: "LogoId"	
  )

  let config = KnotConfiguration(
      sessionId: "session_12345",
      clientId: "client_67890",
      environment: .development,
      entryPoint: "onboarding",
      useCategories: true,
      useSearch: true,
      merchantIds: [52],
      metadata: ["reference_token": "your-token"],
      customerConfiguration: customerConfiguration,
      locale: "es-US"                 // Optional BCP-47 language tag
  )

  Knot.open(configuration: config, delegate: self)
  ```
</CodeGroup>

<Note>
  To ensure seamless integration and avoid any UI issues when embedding the view controller into your UI hierarchy, it's crucial to properly position the view controller within the safe area of your application's interface. This practice helps maintain the accessibility and visibility of the controller across different devices and screen sizes, especially considering the presence of notches, status bars, and navigation elements that might obscure the content.
</Note>

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  class MyViewController : UIViewController {

    func configureKnot() {
      let controller = Knot.createKnotViewController(configuration: session, delegate: delegate)
      view.addSubview(controller.view)
      addChild(controller)
    }

    ...
  }
  ```

  ```Objective-C Objective-C icon=c theme={"system"}
  - (void)configureKnot {

      // 2) If self implements KnotEventDelegate, you can pass `self`; otherwise pass another object conforming to the protocol
      UIViewController *knotViewController =
          [Knot createKnotViewControllerWithConfiguration:config delegate:self];
      
      // 3) Add knotViewController as a child
      [self addChildViewController:knotViewController];
      [self.view addSubview:knotViewController.view];
      knotViewController.view.frame = self.view.bounds; // optionally size it
      [knotViewController didMoveToParentViewController:self];
  }
  ```
</CodeGroup>

<Note>
  To test logging in to a merchant in the SDK, please reference a set of available test credentials for the CardSwitcher product [here](/card-switcher/testing) and Transaction Link product [here](/transaction-link/testing).
</Note>

## Single Merchant Flow

If you decide to use [List Merchants](/api-reference/merchants/list-merchants) to retrieve a list of merchants, list them in your app, and then open the SDK with a single merchant, you can do so by passing a merchant ID when [configuring the session](/sdk/ios#configure-the-session) in the `KnotConfiguration`. More in [Retrieving & Listing Merchants](/link/retrieving-and-listing-merchants). The merchant ID is the same across all environments.

<Info>
  Although available, it is not recommended that you provide a long list of merchants in order to remove a few, but rather "hide" certain merchants that you desire from your [Customer Dashboard](https://dashboard.knotapi.com).
</Info>

## Entry Points

In your app's user experience, you may choose to integrate Knot in one or multiple places (e.g. from different tabs or screens). How users behave when interacting with Knot from each of these "entry points" may vary and it will be useful for you to be able to differentiate these groups of users by entry point in order to assess the conversion and value of each entry point.

You can provide a value for the entry point in `KnotConfiguration.entryPoint` when [configuring the session](/sdk/ios#configure-the-session).  This value will be returned in the `AUTHENTICATED` webhook.

## Categories & Search

Users are presented with a list of merchants in the SDK (unless you provide a single merchant as described above). Accompanying the list is a set of categories and a search experience. Each of these components is visible to users by default (as set in Knot's backend).

You can choose to remove either of them by setting `useCategories: false` and `useSearch: false` in `KnotConfiguration`. **This is not recommended**.

## Events

To receive updates from the SDK, implement `KnotEventDelegate` in your class.

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  class MyViewController: UIViewController, KnotEventDelegate {
      func onSuccess(merchant: String) {
          print("Merchant \(merchant) successfully authenticated.")
      }

      func onError(error: KnotError) {
          print("Error occurred: \(error.errorDescription)")
      }

      func onEvent(event: KnotEvent) {
          print("Received event: \(event.event)")
      }

      func onExit() {
          print("Knot session exited.")
      }
  }
  ```

  ```Objective-C Objective-C icon=c theme={"system"}
  // Make sure to import the generated Swift header, e.g.:
  #import <KnotAPI/KnotAPI-Swift.h>  // or @import KnotAPI;

  @interface MyViewController () <KnotEventDelegate>

  @end

  @implementation MyViewController

  - (void)viewDidLoad {
      [super viewDidLoad];
      // Your setup code here...
  }

  // MARK: - KnotEventDelegate Methods

  - (void)onSuccessWithMerchant:(NSString *)merchant {
      NSLog(@"Merchant %@ successfully authenticated.", merchant);
  }

  - (void)onErrorWithError:(KnotError)error {
      // Because KnotError is an NS_ENUM (NSInteger), it does not expose the Swift-only
      // `errorDescription` property. You can switch on the enum or do something similar:
      NSString *errorDesc;
      switch (error) {
          case KnotErrorInvalidSession:
              errorDesc = @"Invalid session.";
              break;
          case KnotErrorExpiredSession:
              errorDesc = @"Session has expired.";
              break;
          case KnotErrorInvalidClientId:
              errorDesc = @"Invalid client ID.";
              break;
          case KnotErrorInternalError:
              errorDesc = @"An internal error occurred.";
              break;
      }
      NSLog(@"Error occurred: %@", errorDesc);
  }

  - (void)onEventWithEvent:(KnotEvent *)event {
      // event.event is a public NSString property on KnotEvent
      NSLog(@"Received event: %@", event.event);
  }

  - (void)onExit {
      NSLog(@"Knot session exited.");
  }
  ```
</CodeGroup>

### `onSuccess`

This event is called when a user successfully logged in to the merchant and their card was switched. It takes a single string argument containing the name of the merchant.

### `onError`

This event is called when an error occurs during SDK initialization and emits a `KnotError` enum  as described below.

| Error Case           | Description                   | Debugging Steps                                                                                                                                                                                                                                                                                                                                                    |
| -------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| .invalidSession      | The session is invalid.       | Ensure `KnotConfiguration.environment` matches the environment the `sessionId` was created for (`development` or `production`).                                                                                                                                                                                                                                    |
| .expiredSession      | The session has expired.      | Sessions are valid for 30 minutes. It is best practice to ensure that you create a new session **every time** a user invokes the SDK using [Create Session](/api-reference/sessions/create-session).                                                                                                                                                               |
| .invalidClientId     | The client ID is invalid.     | Verify that the value you are providing for `KnotConfiguration.clientId` is for the environment matching the value you are providing for `KnotConfiguration.environment` (i.e. `development` or `production`). If you provide your production `clientId` but set `environment: development`, you will experience this error.                                       |
| .internalError       | An internal error occurred.   | Simply retry invoking the SDK with a new `sessionId`.                                                                                                                                                                                                                                                                                                              |
| .merchantIdNotFound  | The merchant ID is required.  | The `type` of `sessionId` you are providing on invokation of the SDK requires that you also provide a value in `KnotConfiguration.merchantIds` to ensure the user is directed to a specific merchant’s login flow in the SDK. You can retrieve a list of merchant IDs (the same in all environments) in [List Merchants](/api-reference/merchants/list-merchants). |
| .invalidCardName     | The card name is invalid.     | The value you are providing for `customerConfiguration.cardName` must exactly match an allowlisted value for your organization. Please reach out to the Knot team for access to this allowlist.                                                                                                                                                                    |
| .invalidCustomerName | The customer name is invalid. | The value you are providing for `customerConfiguration.customerName` must exactly match an allowlisted value for your organization. Please reach out to the Knot team for access to this allowlist.                                                                                                                                                                |
| .invalidLogoId       | The logo ID is invalid.       | The value you are providing for `customerConfiguration.logoId` must exactly match an allowlisted value for your organization. Please reach out to the Knot team for access to this allowlist.                                                                                                                                                                      |
| .invalidLocale       | The locale is invalid.        | The value you are providing for `KnotConfiguration.locale` must be a valid [BCP-47](https://developer.mozilla.org/en-US/docs/Glossary/BCP_47_language_tag) language tag. Currently supported: `en-US`, `es-US`, `en-CA`, and `fr-CA`.                                                                                                                              |

<Warning>
  Sessions are valid for 30 minutes. If a session expires while the SDK is open, an expired session error will be emitted via `onError` and the SDK will automatically close. To provide a seamless experience, handle the `REFRESH_SESSION_REQUEST` event via the `onEvent` callback to proactively extend the session using [Extend Session](/api-reference/sessions/extend-session) before expiration occurs.
</Warning>

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  func onError(error: KnotError) {
      switch error {
      case .invalidSession:
          print("Error: \(error.errorDescription)")
      case .expiredSession:
          print("Error: \(error.errorDescription)")
      case .invalidClientId:
          print("Error: \(error.errorDescription)")
      case .internalError:
          print("Error: \(error.errorDescription)")
  	case .merchantIdNotFound:
          print("Error: \(error.errorDescription)")
  	case .invalidCardName:
          print("Error: \(error.errorDescription)")
  	case .invalidCustomerName:
          print("Error: \(error.errorDescription)")
  	case .invalidLogoId:
          print("Error: \(error.errorDescription)")
  	case .invalidLocale:
          print("Error: \(error.errorDescription)")
      }
  }
  ```

  ```Objective-C Objective-C icon=c theme={"system"}
  - (void)onErrorWithError:(KnotError)error {
      // Because KnotError is an NS_ENUM (NSInteger), it does not expose the Swift-only
      // `errorDescription` property. You can switch on the enum or do something similar:
      NSString *errorDesc;
      switch (error) {
          case KnotErrorInvalidSession:
              errorDesc = @"The session is invalid.";
              break;
          case KnotErrorExpiredSession:
              errorDesc = @"The session has expired.";
              break;
          case KnotErrorInvalidClientId:
              errorDesc = @"The client ID is invalid.";
              break;
          case KnotErrorInternalError:
              errorDesc = @"An internal error occurred.";
              break;
  		case KnotErrorMerchantIdNotFound:
              errorDesc = @"The merchant ID is required when product type = transaction_link.";
              break;
          case KnotErrorInvalidCardName:
              errorDesc = @"The card name is invalid.";
              break;
          case KnotErrorInvalidCustomerName:
              errorDesc = @"The customer name is invalid.";
              break;
          case KnotErrorInvalidLogoId:
              errorDesc = @"The logo ID is invalid.";
              break;
          case KnotErrorInvalidLocale:
              errorDesc = @"The locale is invalid.";
              break;
      }
      NSLog(@"Error occurred: %@", errorDesc);
  }
  ```
</CodeGroup>

### `onExit`

This event is called when a user closes the SDK.

### `onEvent`

This event is called when certain events occur in the SDK. With this callback, you will be able to understand how a user is progressing through their lifecycle of authenticating to a merchant. It emits a `KnotEvent` class as described below.

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  /// Represents a Knot event received during user interaction within the Knot SDK.
  @objc public class KnotEvent {

      /// The environment the event emitted from
      @objc public let evironment: Environment
      
      /// The product the event emitted from
      @objc public let product: Product
      
      /// The primary event code.
      @objc public let event: String
      
      /// The merchant associated with the event (if applicable).
      @objc public let merchant: String?

  	/// The merchant ID associated with the event (if applicable).
      @objc public let merchantId: String?
      
      /// Additional metadata related to the event, stored as an Objective-C compatible dictionary.
      @objc public let metaData: NSDictionary
      
      /// The identifier associated with this event.
      @objc public let taskId: String?
      
  ...
  }
  ```
</CodeGroup>

The following list contains all possible events emitted in the `KnotEvent.event` property.

| Name                          | Description                                                                                                                                                                             |
| ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| REFRESH\_SESSION\_REQUEST     | Emitted when the session used to initialize the SDK needs to be refreshed. Use [Extend Session](/api-reference/sessions/extend-session) to extend the session before expiration occurs. |
| MERCHANT\_CLICKED             | Emitted when a user clicks on a merchant from the merchant list.                                                                                                                        |
| LOGIN\_STARTED                | Emitted when a user submits their credentials to login to the merchant.                                                                                                                 |
| AUTHENTICATED                 | Emitted when a user successfully logs in to the merchant.                                                                                                                               |
| OTP\_REQUIRED                 | Emitted when a user needs to enter an OTP code to login to the merchant.                                                                                                                |
| SECURITY\_QUESTIONS\_REQUIRED | Emitted when a user needs to enter answers to security questions to login to the merchant.                                                                                              |
| APPROVAL\_REQUIRED            | Emitted when a user needs to approve the login - often via a push notification or directly in the merchant's mobile app - to login to the merchant.                                     |
| ZIPCODE\_REQUIRED             | Emitted when a user needs to enter their zip code to login to the merchant.                                                                                                             |
| LICENSE\_REQUIRED             | Emitted when a user needs to enter their drivers license to login to the merchant.                                                                                                      |

## Other Options

### Get current SDK version

If you need to retrieve the current SDK version for your own use case, implement the following:

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  let sdkVersion = Knot.SDKVersion()
  print("Knot SDK Version: \(sdkVersion ?? "Unknown")")
  ```

  ```Objective-C Objective-C icon=c theme={"system"}
  NSString *sdkVersion = [Knot SDKVersion];
  NSLog(@"Knot SDK Version: %@", sdkVersion ?: @"Unknown");
  ```
</CodeGroup>

### Close the SDK

If you need to explicitly close the SDK, use the below method, otherwise end users will naturally close the SDK as they interact with the interface.

<CodeGroup>
  ```swift Swift icon=swift theme={"system"}
  Knot.close()
  ```

  ```Objective-C Objective-C icon=c theme={"system"}
  [Knot close];
  ```
</CodeGroup>
