Skip to content
andreiqvik edited this page Oct 25, 2023 · 10 revisions

Creating the API client

To initialize the client, you need a configuration key which will point the SDK to your organization. You obtain that from Ninchat. Optionally, you may specify a list of siteconfig environments to use over the default one.

You must keep a reference to the created API client instance until the SDK UI terminates. Using the following code, the SDK can be instaniated:

import NinchatSDKSwift

self.ninchatSession = NINChatSession(configKey: /* CONFIG KEY */)

or in a more advanced way (the NinchatLowLevelClient must be imported).

import NinchatSDKSwift
import NinchatLowLevelClient

self.ninchatSession = NINChatSession(configKey: /* CONFIG KEY */,
                                     queueID: /* QUEUE ID */,
                                     environments: /* ENVIRONMENTS */,
                                     metadata: /* METADATA */,
                                     configuration: /* CONFIGURATION */)

Configuration

Starting version 0.2.5, the SDK can be initiated with a custom configuration that overrides server configurations for any set properties. Available configurations are accessible under NINSiteConfiguration protocol and are described in the upcoming sections.

Username

To override username for the SDK of version 0.2.5 and above, you can use the initialiser in NINSiteConfiguration

/// Define custom configuration
let configuration: NINSiteConfiguration = NINSiteConfigurationImpl(userName: /* USERNAME */)

/// Initiate the SDK using the configuration
let ninchatSession = NINChatSession(configKey: /* CONFIG KEY */,
                                    queueID: /* QUEUE ID */,
                                    environments: /* ENVIRONMENTS */,
                                    metadata: /* METADATA */,
                                    configuration: configuration)

Optional parameters

  • queueID define a valid queue ID to join the queue directly; omit the paramter to show queue selection view.
  • metadata is an optional dictionary that can include some info about the client.
  • environments is optional and may not be required for your deployment.
  • configurationis optional and may be used for different situations.
  • modalPresentationStyleis optional and may be used for setting the modal presentation style of the chat. It has the default value of .fullScreen.

User agent header (Optional)

To append information as the user agent header to your requests, use the following format to set value to appDetails prior to call start(completion:) function:

ninchatSession.appDetails = "app-name/version (more; details)"

Start the API client

The SDK must perform some asynchornous networking tasks before it is ready to use; this is done by calling the start method as follows. The callback includes credentials that could be saved for resuming the session later. The function throws an error if it cannot start the session properly.

self.ninchatSession.delegate = self
try self.ninchatSession.start { (credentials: NINSessionCredentials?, error: Error?) in
    if let error = error {
         /// Some errors in starting a new session.
    }
    /// Save/Cache `credentials` for resuming the session later.
}

Resume a session

The SDK provides support to resume a session. In case of any issues in resuming the session using provided credentials, the corresponded optional delegate is called to ask if a new session should be started or not. The function throws an error if it cannot start the session properly.

self.ninchatSession.delegate = self
try self.ninchatSession.start(credentials: credentials) { (credentials: NINSessionCredentials?, error: Error?) in
    if let error = error {
        /// Some errors in resuming the session.
    }                      
    /// Update saved/cached `credentials` with the new one.
}

Metadata on a session resume

Starting version 0.3.10, the SDK can save and retrive audience metadata directly from the local storage. This makes a host application able to be resumed even if the metadata are not explicitly set. The SDK creates a UserDefaults suite with the name com.ninchat.sdk.swift to cache the metadata, so please be aware to not accidentally override the metadata.

Additionally note that the SDK raises error if the metadata contains an invalid secure token. Ensure you catch errors as described in Catch errors.


Showing the SDK UI

Once you have started the API client, you can retrieve its UI to be displayed in your application's UI stack. Typically you would do this within the start callback upon successful completion. The API can be started with and without using UINavigationController. If the iOS application doesn't provide a valid UINavigationController the SDK will start its own navigation controller.

if let navigation = try self.ninchatSession.chatSession(within: nil) as? UINavigationController {
    self.present(navigation, animated: true)
}

But if the application has a valid UINavigationController, the SDK can be easily pushed on the app's navigation controller.

if let controller = try self.ninchatSession.chatSession(within: self.navigationController) as? UIViewController {
    self.navigationController?.pushViewController(controller, animated: true)
}

Catch errors

Starting version 0.3.10, the SDK supports a better way to catch and handle errors. As an example, you can catch errors related to invalid secure metadata.

func ninchat(_ session: NINChatSession, onLowLevelEvent params: NINLowLevelClientProps, payload: NINLowLevelClientPayload, lastReply: Bool) {
  if case let .success(event) = params.event {
    switch event {
    case "error":
      /// Check generated error
      print("\(params.ninchatError?.type): \(params.ninchatError?.reason)")

      /// Deallocate the session and dismiss/pop the UI
      self.navigationController?.popToViewController(self, animated: true)
      self.ninchatSession.deallocate()
    default:
      break
    }
  }
}

Deallocate SDK

The SDK's API client is to be re-created every time a new chat session is started; once it has terminated, it cannot be used any more and must be disposed of to deallocate memory. To deallocate the session, you must call the following API:

self.ninchatSession.deallocate()

Limitations imposed by the SDK

There are some limitations that the SDK imposes on the host app linking to it:

  • Missing Bitcode support. The host application must be configured to not use bitcode. The SDK's Cocoapods installer will do this automatically.
  • Parts of the SDK are missing the DWARF symbols used for crash symbolication; you must untick the "Include app symbols" checkbox when submitting an app archive to the App Store / TestFlight.

These issues are caused by limitations of the gomobile bind tool used to generate the low-level communications library.