KustomerClient

KustomerClient Class reference for Kustomer Chat iOS Core API .

public class KustomerClient

A singleton. This is how you interact with the Kustomer SDK.

Public vars

chatProvider

Alias for ChatProvider.shared. This provider class is used to interact with all chat related functionality. See ChatProvider.

public var chatProvider: ChatProvider!

pushProvider

Alias for PushProvider.shared.

public var pushProvider: PushProvider

shared

Shared, thread-safe, singleton

public static let shared: KustomerClient

Every method and property of KustomerClient.shared is also available on the Kustomer object. Both are thread-safe singletons.

Kustomer.show()
// is the same as
KustomerClient.shared.show()

status

The status of the KustomerClient

public var status: KustomerClientStatus

bundle

Bundle containing SDK resources

public var bundle: Bundle

sdkVersion

Version of the Kustomer SDK

public var sdkVersion: String { get }

pushKeysPresentAndPushEnabled

public var pushKeysPresentAndPushEnabled: Bool { get }

getSdkVersion(file:line:function:)

Version of the Kustomer SDK

public func getSdkVersion(file: String = #file, line: Int = #line, function: String = #function) -> String

sdkVersionBuild

public var sdkVersionBuild: String { get }

changeActiveAssistant(ActiveAssistantOptions)

Change the ID of the chat assistant used when the user clicks ‘New conversation’.

public func changeActiveAssistant(_ to: ActiveAssistantOptions)

Overrides the default chat assistant from your Kustomer app Chat settings.

The default chat assistant applies to new conversations created

  • Via buttons in the UI
  • Via use of openNewConversation(initialMessages:afterCreateConversation:animated)

Do not use a chat assistant:

Kustomer.changeActiveAssistant(.none)

Use the default chat assistant from your Kustomer website settings, if any:

Kustomer.changeActiveAssistant(.orgDefault)

Use the chat assistant with a specific id

Kustomer.changeActiveAssistant(.withId("12345"))

Example

How to change the chat assistant to a new value, and how to put it back to your organization default

let newId = "a chat assistant ID from your back end"
Kustomer.changeActiveAssistant(.withId(newId))
Kustomer.openNewConversation()

Later, to go back to the assistant ID from your Kustomer web settings:

Kustomer.changeActiveAssistant(.orgDefault)

getActiveAssistantID()

Gets the id, if any, of the chat assistant that will be used next time a new conversation is started.

changeActiveAssistant(ActiveAssistantOptions) changes this value.

public func getActiveAssistantID() -> String?

changeBrand(brandId: completion)

public func changeBrand(brandId:String?, completion: ((Result<Void,KError>)->Void)? = nil )

Changes brand.

If brandId is nil, uses the default brand. If the UI is visible, closes the UI and re-opens it with the new brand.

If the brandId is invalid, returns an error.

changeBusinessSchedule(scheduleId: completion)

public func changeBusinessSchedule(scheduleId:String?, completion: ((Result<Void,KError>)->Void)? = nil )

Changes the business schedule ID. If the UI is visible, it will be updated.

If the schedule ID is invalid, returns an error.

options

The options used to configure the SDK. KustomerOptions for Kustomer. Once passed to configure, they can’t be changed. Never nil.

public var options: KustomerOptions { get }

orgId

The organization ID. Derived from your api key.

public var orgId: String

orgName

Your organization’s name

public var orgName: String { get set }

keychain

A separate iOS keychain for the Kustomer SDK inside your app.

public var keychain: KUSKeychain

useCombinedInterface

 public var useCombinedInterface: Bool { get set }

Initialization

configure(apiKey:options:launchOptions)

Configures the Kustomer SDK.

public func configure(apiKey:String, options:KustomerOptions?, launchOptions: [UIApplication.LaunchOptionsKey: Any]?, completion: ((KustomerConfigurationError) -> ())?)

Configures the Kustomer SDK. See Configuration.

Must be placed in your AppDelegate's application(_:didFinishLaunchingWithOptions:).

apiKey: An API key, with org.tracking permissions.
completion': An optional callback. Used to detect low disk space.

Dynamic properties

Dynamic properties are dependent on the user

isChatAvailable(_:)

Alias for isChatAvailable().

public func isChatAvailable(_ callback: ((Bool) -> Void))

UI

show()

Shows the Knowledge Base in the default view. Alias for Kustomer.show(.default).

public func show()

show(preferredView:KustomerDisplayMode)

public func show(preferredView: KustomerDisplayMode)

Shows the Kustomer chat UI. The Kustomer chat UI lets the Customer view their chat history, start a new chat, and browse the knowledge base.

Open the UI using the widget settings from the Kustomer admin website:

Kustomer.show(preferredView: .default)

Open the UI to a new conversation, using the chat settings from your Kustomer admin website:

  • Works the same as the large blue "New conversation" button in the UI. For example, if "restrict to single open chat" is turned on, and the customer has an open chat, Kustomer.show(preferredView: .newChat) will open the existing open chat.
Kustomer.show(preferredView: .newChat)

Open the UI to the currently active chat, or creates a new chat if there isn't one:

  • If the customer has an existing open chat, opens it.
  • If not, creates a new conversation and opens it
Kustomer.show(preferredView: .activeChat)

Open the UI to the chat history screen. Uses the widget settings from the Kustomer admin website to decide if a tab bar should be shown:

Kustomer.show(preferredView: .chatHistory)

Open the UI to the knowledge base screen:

  • Use the widget settings from the Kustomer admin settings to decide if a tab bar should be shown.
Kustomer.show(preferredView: .knowledgeBase)

Hide the bottom tab bar and opens the UI to the chat history screen:

Kustomer.show(preferredView: .onlyChat)

Hide the bottom tab bar and opens the UI to the knowledge base screen:

Kustomer.show(preferredView: .onlyKnowledgeBase)

openConversation(id:animated:completion)

Opens an existing conversation.

public func openConversation(id:String, animated:Bool = true, completion: ((Result<KUSConversation,KError>)->Void)? = nil)

Open a conversation with the specified ID:

Kustomer.openConversation(id: "5fcb96a3c67a7f0096ac4fc7")

To hide the animation from the chat history screen to the conversation screen, use the animated parameter:

Kustomer.openConversation(id: "5fcb96a3c67a7f0096ac4fc7", animated: false)

Use the optional completion block to handle errors and invalid conversation IDs, and to get info about the opened conversation

Kustomer.openConversation(id: "5fcb96a3c67a7f0096ac4fc7", completion: { (result:Result<KUSConversation, KError>) in
  switch result {
  case .success(let conversation):
    print(conversation.id)
  case .failure(let error):
    print(error)
  }
})

If the id is invalid, the user interface will not be shown.

Deprecated Use startNewConversation

openNewConversation(initialMessages:afterCreateConversation:animated)

startNewConversation(initialMessage:presentingVC:afterCreateConversation:animated:)

public func startNewConversation(initialMessage: KUSInitialMessage? = nil,
                                 presentingVC: UIViewController? = nil,
                                 afterCreateConversation: ((KUSConversation)->Void)? = nil,
                                 animated: Bool = true)

Opens a new conversation.

Kustomer.startNewConversation()

💡If you have a default chat assistant enabled, the new conversation will use this default assistant.

To skip the animation from the chat history screen to the conversation screen, use the animated parameter:

Kustomer.startNewConversation(animated:false)

To pre-populate the chat with an outgoing or incoming text message, add an initialMessage parameter:

let initialMessage = KUSInitialMessage(body: "Hi, I need help", direction: .user)
Kustomer.startNewConversation(initialMessage: initialMessage)

💡If you have a default chat assistant, initialMessages from .agent are ignored

To access the conversation after the customer has replied, use the afterCreateConversation parameter. afterCreateConversation runs only after the customer sends their first message.

Kustomer.startNewConversation(afterCreateConversation: { (conversation:KUSConversation) in
  print(conversation.id)
})

openChatAssistant(id:completion:afterFirstMessage:)

  public func openChatAssistant(id: String,
                                startDialog: String?,
                                presentingVC: UIViewController? = nil,
                                completion: @escaping ((Result<Void,KError>)->Void),
                                afterFirstMessage: @escaping ((KUSConversation)->Void) = { c in },
                                initialMessages:[String]? = nil,
                                animated:Bool = true)

Starts a new chat with our bot using the passed chat assistant ID.

id: The ID of the desired chat assistant
startDialog: Any opening dialog you wish to append to the chat assistant
presentingVC: A reference to the view controller that is presenting the chat interface, if nil the Kustomer SDK will attempt to derive it
completion: If you were able to start chatting with this assistant, success, otherwise an error
afterFirstMessage: Runs after the first customer-submitted response is processed fully.
initialMessages: The initial messages from the customer
animated: Whether or not to animate the presentation. Defaults to 'true'

showKbArticle(id:)

Opens the knowledge base screen and tries to show an article with the given id.

public func showKbArticle(id:String)
Kustomer.showKbArticle(id: "5ec9b34732382e0014688aa0")

If the id is invalid, the UI shows an error message.

showKbCategory(id:)

Opens the knowledge base screen and loads a specific category with the given id.

public func showKbCategory(id:String)

If the id is invalid, the UI shows an error message.

printLocalizationKeys()

public func printLocalizationKeys()

Prints all localized keys available in SDK. Uses the same format as a .strings file. See Localization.

close()

Closes the chat UI.

public func close()

close()

Closes the Kustomer UI if it's open. The completion block is called after the KustomerOptions.onDismiss block.

public func close(animated: Bool = true, completion: (() -> Void)?)

isVisible()

Check if your chat UI is currently visible (open or closed).

public func isVisible()

Log in and log out

Logging in and out

logIn

public func logIn(jwt: String, _ completion: @escaping ((Result<Void, KError>) -> Void))

Securely identify a customer w/ the passed JWT. Loads all their chat histories in the background, as network conditions permit.

  • If there are chats already started, links them to this customer.
  • If the customer has any chat history from other devices, loads that history onto this device.
  • May trigger merges and moves of customers and conversations
Kustomer.logIn(jwt: "foo") { result in
  switch result {
  case .success:
    print("logged in")
  case .failure(let error):
    print(error)
  }
}

logOut

public func logOut(_ completion: @escaping ((KError?) -> Void))

Logs out the customer. Clears the customer's access to any existing chats from the device. If you’re using push, deregisters them from the Kustomer push service.

  • Can fail if you’re using push notifications and we’re unable to deregister them from future pushes (e.g. if they try to log out while there is no internet).
  • Can not fail if you’re not using push notifications.
  • Returns immediately if you're not using push notifications
  • Returns immediately if you are using push notifications but the device/user hasn't registered for push
Kustomer.logOut({ error in
    if error != nil {
        print(“there was a problem (error?.localizedDescription)”)
    }
})

logOutThenLogIn

public func logOutThenLogIn(jwt:String, _ completion:@escaping ((Result<Void,KError>)->Void))

Signs out the current customer if there is one. Then logs in as the customer with the JWT passed. Loads all their chat histories in the background, as network conditions permit.

identifyCurrentCustomer(jwt:_:)

public func identifyCurrentCustomer(jwt: String, _ completion: @escaping ((Result<Void, KError>) -> Void))

Push notifications

didFailToRegisterForRemoteNotifications(error:)

If you’re using our push notifications, place this in your AppDelegate’s application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) method

public func didFailToRegisterForRemoteNotifications(error: Error)

didRegisterForRemoteNotifications(deviceToken:)

If you are using push notifications in the KustomerChat call this function in your own AppDelegate, passing the parameters from func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)

application: Pass the application object that is passed to your AppDelegate
deviceToken: Pass the deviceToken object that is passed to your AppDelegate

public func didRegisterForRemoteNotifications(deviceToken: Data)

deregisterCurrentDeviceForPushNotifications(_:)

Alias for PushProvider.deregisterCurrentDeviceForPushNotifications(...)

public func deregisterCurrentDeviceForPushNotifications(_ completion: @escaping ((Result<Void, KError>) -> Void))

requestAuthorizationForPush()

Alias for PushProvider.requestAuthorizationForPush(...)

public func requestAuthorizationForPush()

Reconnect to pub/sub

reconnect()

Use to reconnect manually.

(Core SDK only - if you’re using our UI you should never call this method)

Tries to reconnect, and you can monitor the progress via events from KUSConnectionProvider . Used to manually re-connect after the internet goes away and comes back.

Note: In most cases you won’t need to use this.

Use either after calling stop(), or after handling an onConnectionStatusChange(status:KustomerConnectionStatus) with a status of .connected (see KUSConnectionProvider)

public func reconnect()

stop()

Disconnects from pubsub, stops receiving all events.

(Core SDK only - if you’re using our UI you should never call this method)

If you want to go back online, use reconnect()

public func stop()

Start the client

start(completion:failure:)

Creates the connection to the Kustomer SDK backend.

completion: A block that is passed a Result type. If the connection was created successfully this enum will be .success, if the connection failed it will be .failure(error) and will have error information. There are no automatic retries.

public func start(completion: @escaping (() -> Void), failure: @escaping ((Error) -> Void))

start()

Alias for KustomerClient.start(...) with no callbacks. Use if you don’t care if the client starts or not. The client will auto start whenever the UI is shown, if you’re using the UI.

public func start()

start(completion:)

Alias for KustomerClient.start(...) with only a completion callback

public func start(completion: @escaping (() -> Void))

start(failure:)

Alias for KustomerClient.start(...) with only a failure callback

public func start(failure: @escaping ((Error) -> Void))

Settings and schedules

unUserNotificationCenterDelegate

public var unUserNotificationCenterDelegate: UNUserNotificationCenterDelegate?

If you have Kustomer Push Notifications enabled, set this to your own UNUserNotificationCenterDelegate to process remote and/or local notifications that don't come from Kustomer. This ensures that your delegate will not receive any pushes from Kustomer.

If you are not using Kustomer push notifications, you will not need this.

Wrappers for ChatProvider methods

getUnreadCount(completion:)

public func getUnreadCount(completion: @escaping (Result<Int, KError>) -> Void)

Alias for getUnreadCount(completion:).

getUnreadCount()

❗️

Deprecated: Use getUnreadCount(completion:) instead.

public func getUnreadCount() -> Int

Alias for unreadCount().

getOpenConversationCount(completion:)

The number of open conversations for the current customer.

Alias for ChatProvider.getOpenConversationCount(completion:).

public func getOpenConversationCount(completion: @escaping (Result<Int, KError>) -> Void)

openConversationCount()

❗️

Deprecated: Use getOpenConversationCount(completion:) instead.

The number of open conversations for the current customer. Returns immediately. If there is no current customer, returns 0.

Alias for ChatProvider.openConversationCount(...).

public func openConversationCount() -> Int

Reset

removeAllSessionsAndRelatedData()

Removes all conversations and messages. Keeps the customer logged in. Keeps the SDK connected to pubsub and our platform.

@available(*, deprecated)
public func removeAllSessionsAndRelatedData()