icon-people 7 days of no-limit free trial. Try now! icon-people
en
ru

SDK configuration (iOS)

The simplest way to add the Chat2Desk libraries to your Xcode project is by using CocoaPods.

Getting Started with CocoaPods

  1. Install CocoaPods (see CocoaPods Getting Started Guide)

  2. If you don't have a Podfile, create one by running pod init in the project directory.

  3. Add a Chat2Desk dependency to the Podfile.

    platform :ios, '9.0'

    target 'SDK Demo' do
       use_frameworks!
       pod 'chat2desk_sdk'
    end

  4. Run pod install command in the project directory to install the SDK.

  5. Open your project via the .xcworkspace file you just created.

SDK initialization

Firstly, declare the Background modes. Go to the main file of your project, Singing & Capabilities tab, click the "+" button at the top and select Background modes.

Now you are ready to create an instance of Chat2Desk client. To do this, import chat2desk_sdk into your swift class and create an instance of IChat2Desk as shown below:

let settings = Settings.init(
    authToken: "WIDGET_TOKEN",
    baseHost: "BASE_HOST",
    wsHost: "WS_HOST",
    storageHost: "STORAGE_HOST"
)
let chat2desk = Chat2Desk.Companion().create(settings: settings)

You need to obtain WIDGET_TOKEN, BASE_HOST, WS_HOST, and STORAGE_HOST from the Settings > Widget + Online Chat page for the specific connected channel.

Uninstalling the SDK

Use the IChat2Desk.close method before deleting the IChat2Desk instance to prevent memory leaks.

Connecting and disconnecting

Use IChat2Desk.start method for connecting to the service and IChat2Desk.stop to disconnect from it.

You can track the connection status through the watchConnectionStatus(): СFlow<ConnectionState>.

Refer to this code example to get an idea of how it works:

class SomeClass: ObservableObject {
    @Published public var connectionStatus: ConnectionState? = nil
    
    let chat2desk: Chat2Desk
    
    var connectionStatusWatcher: Closeable?
    
    init(chat2desk: Chat2Desk) {
        self.chat2desk = chat2desk
        
        connectionStatusWatcher = chat2desk.watchConnectionStatus().watch { status in
            self.connectionStatus = status
        }
    }
    
    func start() {
        Task {
            try await chat2desk.start()
        }
    }
    
    func stop() {
        Task {
            try await chat2desk.stop()
        }
    }
    
    deinit {
        connectionStatusWatcher?.close()
    }
}

Receiving messages

To work with messages, the library must be connected to the Chat2Desk service.

All incoming and outgoing messages are cached inside the library by default and can be accessed offline.

To get a list of messages, use the watchMessages(): CFlow<[Message]> property:

chat2desk.watchMessages.watch { messages in
    print(messages)
}

Fetching messages from the server

To work with messages, the library must be connected to Chat2Desk.

IMPORTANT: SDK fetches a maximum of 100 messages from the server at a time

  1. chat2desk.fetchMessages() – Fetches the last 100 messages.
  2. chat2desk.fetchNewMessages() – Fetches new messages newer than the last message on the device.
  3. chat2desk.fetchMessages(loadMore: true) – Fetches older messages, up to 100 at a time, older than the first message on the device.

Searching Messages

The SDK supports two ways to search messages: full-text search and search through operators. Both methods search messages based on the Message.text property and return a list of [Message].

Full-Text Search:

chat2desk.fullTextSearch(query: String): [Message]

Words in the query are tokenized as follows:

  • Tokens can only consist of ASCII and Latin-1 characters. All other characters are treated as spaces.
  • Words separated by a hyphen (-) are split into two tokens. For example, full-text becomes full and text.
  • Tokens are case-insensitive and diacritic-insensitive.

You can search for a whole word, a phrase, or refine results using the following characters:

  • Exclude results by placing a - before a word (e.g., fiction -science).
  • Use a prefix search by adding * at the end of a word (e.g., fict* for fiction and fictitious). (Suffix search is not supported by the SDK.)

Operator-Based Search:

chat2desk.searchByQuery(query: String, options: SearchOptions?): [Message]

SearchOptions.init(
  /**
    * Оператор поиска
    */
  operator: QueryStringOperator.contains, 
  /**
    * Case sensitivity.
    * Only for ASCII and Latin-1 characters
    */
  caseSensitivity: false
)

enum QueryStringOperator {
    case beginswith
    case contains
    case endswith
    case like
    case equal
    case notequal
}

You can specify the operator to search messages with the following options:

 

Operator Description
beginswith Matches if the left string begins with the right string.
contains Matches if the right string is found anywhere in the left string.
endswith Matches if the left string ends with the right string.
like Matches if the left string matches the right wildcard string (e.g., d?g matches dog, dig, dug).
equal Matches if the left string is lexicographically equal to the right string.
notequal Matches if the left string is not lexicographically equal to the right string.

Sending Messages

To work with messages, the library must be connected to the Chat2Desk service.

  • Send a message: sendMessage(msg: String)

chat2desk.sendMessage(msg: txt)

  • Send message with attachment: sendMessage(msg: String, attachedFile: AttachedFile). To send an attachment, you need to create an instance of the class AttachedFile and pass it to the method.

let attachedFile = AttachedFile.Companion().fromURL(url: url, originalName: originalName, mimeType: mimeType, fileSize: fileSize)
chat2desk.sendMessage(msg: txt, attachedFile: attachedFile)

  • Resend message: resendMessage(message: Message).

chat2desk.resendMessage(message: message)

Sending Client Information

The service allows sending client information. By default, two fields are available: name and phone.

chat2desk.sendClientParams(name: String, phone: String)

The service also passes a list of custom fields defined in the company: customFields: CFlow<[CustomField]>.

var fields: [CustomField] = []

chat2desk.watchCustomFields().watch { customFields in
    self.fields = customFields?.compactMap({ $0 as? CustomField }) ?? []
}
let fieldSet: [KotlinInt: String] = [KotlinInt(value: self.fields[0].id): "value"]

Task {
  try await chat2desk.sendClientParams(name: "name", phone: "phone", fieldSet: fieldSet)
}

Additional Settings

  • Information about the operator: operator: CFlow<Operator?>

chat2desk.watchOperator().watch { operator in
  print(operator)
}

  • Receiving errors: error: CFlow<Throwable?>

chat2desk.watchError().watch { error in
  print(error.message)
}

Demo

Swift SDK Demo demonstrates basic SDK functionality

Related articles