Chat Consultation
ChatConfig Object
For chat
consultations, the consultation data will include the ChatConfig
object
This config data will be used to initiate and handle the chat between the user and the doctor
struct ChatConfig {
id: Int?
consultationId: Int?
groupId: String?
chatUserId: String?
appId: String?
chatUserToken: String?
}
Chat Initialization
From the Consultation data, just use the chatConfig
to initialize the chat
import AltibbiTelehealth
import SendbirdChatSDK
import MobileCoreServices // For Image and File Pickers and handling sending them
if let info = consultationInfo, let config = info.chatConfig {
AltibbiChat.initialize(config: config!)
}
Adding Event Listeners and Handlers
Handle chat connection and events by implementing the related protocols
GroupChannelDelegate
, ConnectionDelegate
// Connection Delegate
func didDisconnect(userId: String) {
print("ConnectionDelegate >>> didDisconnect user id: \(userId)")
}
// Group Channel Delegate
func channel(_ channel: BaseChannel, didReceive message: BaseMessage) {
// This is to handle the received messages
self.messages += [message]
}
func channel(_ channel: GroupChannel, userDidLeave user: SendbirdChatSDK.User) {
// This is to handle if the user left tha chat
// It also indicates the consultation is closed
}
func channelDidUpdateTypingStatus(_ channel: GroupChannel) {
// This reflects the typing status for the other side of the chat
if channel.isTyping() {
self.typingLbl.text = "Typing..."
} else {
self.typingLbl.text = ""
}
}
Handle Chat Display
Handle Chat display by using UITableView and implementing the related protocols
UITableViewDataSource
, UITableViewDelegate
var messages: [BaseMessage] = []
@IBOutlet weak var tableView: UITableView!
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let message = messages[indexPath.row]
if message.sender?.userId == (consultationInfo?.chatConfig?.chatUserId)! {
let cell = tableView.dequeueReusableCell(withIdentifier: "MyMessageCell", for: indexPath) as! MyMessageCell
cell.configure(with: message)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageCell
cell.configure(with: message)
return cell
}
}
override func viewDidLoad() {
tableView.delegate = self
tableView.dataSource = self
// Registering chat cell for TableView
tableView.register(UINib(nibName: "MyMessageCell", bundle: nil), forCellReuseIdentifier: "MyMessageCell")
tableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "MessageCell")
// MARK: File messages could be handled by checking if the message is a link then a new custom cell is needed
}
Loading All Channel Messages
On first load or at any exit and re-enter to the chat screen, you have to load the previous messages of the channel
Make sure this step is done after
AltibbiChat.initialize()
so thatAltibbiChat.chatChannel
could be ready to load the messages
Check the code below:
var query: PreviousMessageListQuery?
// After initialization
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
self.query = AltibbiChat.chatChannel!.createPreviousMessageListQuery { params in
params.limit = 200
params.reverse = false
}
self.query!.loadNextPage(completionHandler: { messages, error in
guard error == nil else {
// Check Error
return
}
if let oldMessages = messages {
DispatchQueue.main.async {
self.messages += oldMessages
self.tableView.reloadData()
self.scrollToBottom()
SendbirdChat.addChannelDelegate(self, identifier: "Channel_Delegate_\(config.groupId ?? "000000")")
SendbirdChat.addConnectionDelegate(self, identifier: "Connection_Delegate_\(config.groupId ?? "000000")")
}
}
})
}
Sending Messages
Once the chat is initiated you can start sending messages using sendUserMessage
from the AltibbiChat.chatChannel
instance
with the message String
Check the code below:
AltibbiChat.chatChannel!.sendUserMessage(msg, completionHandler: {userMsg, error in
if error != nil {
print("sendUserMessage ERROR >>> \(error!.localizedDescription)")
}
if let sentMessage: BaseMessage = userMsg {
DispatchQueue.main.async {
self.messages += [sentMessage]
self.tableView.reloadData()
}
}
})
Sending media files (Pictures or PDFs)
You can send pictures and PDF files on the chat using uploadMedia
previously mentioned in create consultation section
Once you upload a file, you'll get an object of Media and you can use the url
and send it as a message
For displaying these media messages, you can check if the message includes cdn
or pdf