ChatProvider

ChatProvider Class reference for Kustomer Chat iOS Core API .

public class ChatProvider

shared

The central object for managing non-UI Kustomer chat related activities

public static let shared: ChatProvider

Listeners

All currently registered KUSChatListeners.

public var listeners: [String : KUSChatListener]

addChatListener(_:)

Register a KusChatListener to the Core SDK to receive chat events.

public func addChatListener(_ listener: KUSChatListener) -> String

removeChatListener(_:)

Unregister a KUSChatListener using its unique String identifier.

public func removeChatListener(_ uuid: String)

removeAllChatListeners()

Removes all registered KUSChatListeners from the Core SDK.

public func removeAllChatListeners()

listenForTyping(conversationId:)

Begins listening for typing events.

public func listenForTyping(conversationId: String)

stopListeningForTyping(conversationId:)

Stops listening for typing events.

public func stopListeningForTyping(conversationId: String)

Reading data

getConversations(completion:)

Fetch all conversations for the current customer. Warning: this function will eagerly fetch all conversations for the active user and may be slow to complete for users with a large conversation history. For more efficient loading use getConversationPage.

public func getConversations(completion: @escaping (Result<[KUSConversation], KError>) -> Void)

getConversationPage(page:pageSize:completion:)

Fetch a page of conversations for the current customer.

public func getConversationPage(page: Int, pageSize: Int, completion: @escaping (Result<[KUSConversation], KError>) -> Void)

getConversations()

❗️

This function is removed in version 2.7.0. Use getConversations(completion:) instead.

All conversations for the current customer.

Immediately returns last known list of conversations for the current customer from the SDK’s persistent offline storage.

public func getConversations() -> [KUSConversation]

getConversation(conversationId:completion:)

Calls the completion with a Result containing the KUSConversation object for the given id in the success case, or an error in the failure case.

public func getConversation(conversationId: String, completion: @escaping (Result<KUSConversation, KError>) -> Void)

getConversation(conversationId:)

❗️

This function is removed in version 2.7.0. Use getConversation(conversationId:completion:) instead.

Returns a KUSConversation object for the given id. Returns nil if the ID is not found.

public func getConversation(conversationId: String) -> KUSConversation?

chatMessages(conversationId:)

❗️

This function is removed in version 2.7.0. Use getChatMessages(conversationId:completion:) instead.

Immediately returns last known list of messages for a conversation. Use a KUSChatListener to be notified when new messages come in.

public func chatMessages(conversationId: String) -> [KUSChatMessage]

getChatMessages(conversationId:completion:)

Gets the messages for a conversation using a network call to Pubnub history (up to 30 days).

public func getChatMessages(conversationId:String, completion: @escaping (Result<[KUSChatMessage],KError>) -> Void)

getHistoricChatMessages(conversationId:completion:)

Gets the messages for a conversation from Kustomer API. Warning: this function will eagerly fetch all pages of messages for the given conversation. To fetch messages in pages use getChatMessagesBefore.

public func getHistoricChatMessages(conversationId: String, completion: @escaping (Result<[KUSChatMessage], KError>) -> Void)

getChatMessagesBefore(timestamp:conversationId:count:completion:)

Gets the chat messages for a conversation before a given timestamp. Note: the array of messages in the completion will be sorted in reverse chronological order.

public func getChatMessagesBefore(timestamp: Date, conversationId: String, count: Int, completion: @escaping (Result<[KUSChatMessage], KError>) -> Void)

getInitialMessages(assistantId:startDialog:completion:)

Gets the initial messages for the active chat assistant, to be displayed right away. You can then call createConversation to create a chat assistant conversation on the backend once the user replies to an initial message. The active assistant id and start dialog will be used if the parameters are not provided.

public func getInitialMessages(assistantId: String? = nil,
                               startDialog: String? = nil,
                               completion: @escaping (Result<[KUSChatMessage], KError>) -> Void)

getUnreadCount(completion:)

Fetches the unread count and calls the completion with a Result containing the unread count in the success case or an error in the failure case. Use a KUSChatListener to be notified when the unread count changes.

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

unreadCount()

❗️

This function is removed in version 2.7.0. Use getUnreadCount(completion:) instead.

Immediately returns the current customer’s unread count. Use a KUSChatListener to be notified when this changes.

public func unreadCount() -> Int

getOpenConversationCount(completion:)

Fetches the open conversation count and calls the completion with a Result containing the count in the success case or an error in the failure case.

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

openConversationCount()

❗️

This function is removed in version 2.7.0. Use getOpenConversationCount(completion:) instead.

public func openConversationCount() -> Int

currentCustomer()

❗️

This function is removed in version 2.7.0 Use customerExists() instead.

Information about the current customer. Value is persisted across application restarts.

Is nil if you have not successfully called logIn(...) and there are no anonymous chats.

Anonymous chats are chats created by users who have not called logIn(...).

After logOut(...) this becomes nil.

public func currentCustomer() -> KUSCustomer?

customerExists()

Returns true if there is a current Customer (either anonymous or logged-in) in the Kustomer system.

public func customerExists() -> Bool

getChatSettings()

Returns chat settings. Does not attempt to load or update them from the REST API.

public func getChatSettings() -> KUSChatSettings

isChatAvailable(_:)

Check the “turned on/off” status of your chat within Business Hours and outside of Holidays settings asynchronously. For example, if chat is turned off or outside of business hours, you may want to turn off the button or deflect customers to contact an email).

If you change your business hours or holidays in the admin panel, you must restart the app to see the new values.

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

Writing data

createConversation(firstCustomerMessage:completion:)

Creates a conversation with a message, action, mll node, image, or file url (one of these must be provided). Title and descriptors for the conversation can also be included.

  public func createConversation(firstCustomerMessage text: String? = nil,
title: String? = nil, customDescribe: KUSCustomDescribe? = nil, action: KUSMessageAction? = nil, mllNode: KUSMLLNode? = nil, image: UIImage? = nil, fileURL: URL? = nil, completion: @escaping ((Result<(conversation: KUSConversation, messages: [KUSChatMessage], customer: KUSCustomer?), KError>) -> Void))

sendChatMessage(action:conversationId:completion:)

Reply to a message from a chat assistant using an action (action == a quick reply button)

public func sendChatMessage(action: KUSMessageAction, conversationId: String, completion _outerCompletion: @escaping (Result<(message: KUSChatMessage, conversation: KUSConversation), KError>) -> Void)

sendChatMessage(action:completion:)

❗️

This function is removed in version 2.7.0. Use sendChatMessage(action:conversationId:completion:) instead.

Reply to a message from a chat assistant using an action (action == a quick reply button)

public func sendChatMessage(action: KUSMessageAction, completion _outerCompletion: @escaping (KUSChatMessage, KUSConversation) -> Void)

sendChatMessage(text:assistant:conversationId:completion:)

Sends a text message as a reply to a chat assistant question.

public func sendChatMessage(text: String, assistant: KUSAssistant, conversationId: String, completion _outerCompletion: @escaping (Result<(message: KUSChatMessage, conversation: KUSConversation), KError>) -> Void)

📘

For non-conversational-assistant conversations, use sendChatMessage(text:String, conversationId:String, completion: @escaping ((KError?) -> Void)) instead.

sendChatMessage(text:assistant:completion:)

❗️

This function is removed in version 2.7.0. Use sendChatMessage(text:assistant:conversationId:completion:) instead.

Sends a text message as a reply to a chat assistant question.

public func sendChatMessage(text: String, assistant: KUSAssistant, completion _outerCompletion: @escaping (KUSChatMessage, KUSConversation) -> Void)

sendChatMessage(mllNode:conversationId:completion:)

Reply to a message from a chat assistant using an MLL node

public func sendChatMessage(mllNode: KUSMLLNode, conversationId: String, completion _outerCompletion: @escaping (Result<(message: KUSChatMessage, conversation: KUSConversation), KError>) -> Void)

sendChatMessage(mllNode:completion:)

❗️

This function is removed in version 2.7.0. Use sendChatMessage(mllNode:conversationId:completion:) instead.

Reply to a message from a chat assistant using an MLL node

public func sendChatMessage(mllNode: KUSMLLNode, completion _outerCompletion: @escaping (KUSChatMessage, KUSConversation) -> Void)

sendChatMessage(image:conversationId:completion:)

Posts a message containing an image to a conversation.

public func sendChatMessage(image:UIImage,
                                conversationId:String,
                                completion: @escaping ((KError?) -> Void))

sendChatMessage(fileUrl:conversationId:completion:)

Posts a message containing a file or video to a conversation.

public func sendChatMessage(fileUrl:URL,
                                conversationId:String,
                                completion: @escaping ((KError?) -> Void))

createAssistant(id:after:error:afterCreateConversation:)

❗️

Deprecated: Use getInitialMessages to get the initial assistant messages to display, and createConversation to create the conversation when the user responds to an initial assistant message. This function will not work as of version 2.7.0

Creates a new KUSAssistant. Fetches the properties needed to use this assistant. Gets a list of initialMessages that are the same format as KUSChatMessage. A conversation (KUSConversation) on our system (that shows up on the Kustomer website) is not created. A KUSConversation is only created after you submit a message using this assistant.

1.  When a conversation is created, you will get notifications for each message in `initialMessage`s, but they will have different `id`s and potentially `createdAt` dates.

2.  `initialMessages` is a template for what you should show your customer. They aren’t actual `KUSChatMessages` that are on our platform.
 public func createAssistant(id: String,
                                after: @escaping ((KUSAssistant) -> Void),
                                error: @escaping ((KError) -> Void),
                                afterCreateConversation: ((KUSConversation)->Void)? = { _ in }) -> String

endConversation(conversationId:completion:)

Ends an existing conversation.

public func endConversation(conversationId: String, completion: @escaping ((Result<KUSConversation, KError>) -> Void))

reloadChatSettings(_:)

Reloads chat settings and business schedules from our REST API. If the network call fails, returns an error.

public func reloadChatSettings(_ callback: @escaping ((KError?) -> Void))

describeConversation(conversationId:attributes:_:)

Attach custom attributes to the user’s most recent conversation (or the first one they create).

See Describe Conversation.

public func describeConversation(conversationId: String, attributes: [String : Any], _ completion: @escaping ((Result<Void, KError>) -> Void))

🚧

These key-value pairs must be activated on the Conversation Klass via the admin portal. This can be done by an admin via Settings > Platform Settings > Klasses > Conversation.

- attributes: A dictionary with the custom information for the Session. You can pass this any key/value pair and the backend will add that information as Custom fields. The type name is appended to the end of the custom field. So if you see a custom string field on your admin dashboard called `favoriteColor`, you should pass `favoriteColorStr` to this method. Suffixes are: `Num` for numbers, `Tree` for multi-level lists, `Bool` for true/false, `Url` for urls, `Str` for strings.

Example:

`self.describe(attributes: ["aNumberNum": 10, "aMlListTree": "scotland", "aDateAt":Date(), "aTrueFalseBool": true, "aUrlUrl":"https://www.apple.com", "favoriteColorStr":"Blue"]) { result in switch result { case .success: kprint("Ok") case .failure(let error): kprint(error.localizedDescription) if case let .describeUnknownParameter(parameter: p, details: details) = error { kprint("unknown param is \(p)") kprint(details!) } if case let .describeParameterWrongType(parameter: p, details: details) = error { kprint("wrong type param is \(p)") kprint(details!) } } }`

describeCurrentCustomer(phone: email:phones:emails:facebook:instagram:twitter:linkedIn:custom:_:)

Attach custom attributes to the customer.

See Describe Customer.

public func describeCurrentCustomer(phone: String? = nil, email: String? = nil, phones: [String]? = nil, emails: [String]? = nil, facebook: String? = nil, instagram: String? = nil, twitter: String? = nil, linkedIn: String? = nil, custom: [String : Any]? = nil, _ completion: ((Result<Void, KError>) -> Void)? = nil)

📘

Attached key-value pairs via the custom property must be enabled on the Customer Klass via the admin portal. This can be done by an admin via Settings > Platform Settings > Klasses > Customer, and works the same way as describeConversation

markRead(conversationId:)

Marks a conversation as read as of right now. Any message received for this conversation after this will be treated as unread, until marked read again. This function should be called whenever the user closes the chat view for a conversation.

public func markRead(conversationId: String)

markRead(conversationId:messageIds)

Marks a conversation as read as of right now, and marks the message IDs as read so they show up as Seen on the agent timeline. Any message received for this conversation after this will be treated as unread, until marked read again. This function should be called in place of markRead(conversationId:) to avoid redundant network calls when the IDs of the unread messages are known. For example, when a message arrives to an open conversation.

public func markRead(conversationId: String, messageIds: [String)

submitSatisfactionForm(conversationSatisfactionId:)

Submits the user's response to a satisfaction form.

public func submitSatisfactionForm(conversationSatisfactionId: String,
                                     response: KUSCSATNetworkPostBody,
                                     conversationId: String,
                                     completion: @escaping ((Result<KUSSatisfaction, KError>) -> Void)) {
    chatMessageRepository.submitSatisfactionForm(conversationSatisfactionId: conversationSatisfactionId, response: response) { [weak self] result in
      switch result {
      case .success(let satisfaction):
        self?.conversationRepository.getConversation(conversationId) { [weak self] result in
          switch result {
          case .success(let conversation):
            guard let conversationChannel = conversation.channels.first(where: { $0.type == .conversation }) else {
              completion(.failure(.named("Failed to submit satisfaction form to PubNub, Could not find conversation channel.")))
              return
            }
            self?.pubSubService.sendSatisfaction(for: conversationChannel.name, satisfaction: satisfaction, completion: completion)
          case .failure(let error):
            completion(.failure(.generic(error)))
          }
        }
      case .failure(let error):
        completion(.failure(.generic(error)))
      }
    }
  }
ParameterDescription
conversationSatisfactionIdID for the CSAT item. This will be in the KUSSatisfaction object passed in onSatisfactionEventReceived.
responseHolds the data to be submitted in response to the form.
conversationIdID for the conversation associated with the CSAT.
completionTo be invoked on success or failure submitting the form

Identifying

See Log in and authentication.

identify(jwt:_:)

❗️

Deprecated:See Log in and authentication.

willCrash()

public func willCrash()