ShortCut Formatter
Introduction
The ShortCutFormatter class extends the CometChatTextFormatter class to provide a mechanism for handling shortcuts within messages. This guide will walk you through the process of using ShortCutFormatter to implement shortcut extensions in your CometChat application.
Setup
- Create the ShortCutFormatter Class: Define the
ShortCutFormatterclass by extending theCometChatTextFormatterclass.
- Swift
class ShortcutFormatter: CometChatTextFormatter {
private var messageShortcuts: [String: String] = [String: String]( )
private var shortcuts: [CometChatUIKitSwift.SuggestionItem] = []
}
- initializer: Sets the
trackingCharacterto '!' in the initializer of theShortcutFormatterclass
- Swift
override init(trackingCharacter: Character) {
super.init(trackingCharacter: "!")
}
- Prepare Regex: Set the regular expression for shortcut detection in the
getRegex()method ofShortcutFormatterclass.
- Swift
override func getRegex() -> String {
return "(^|\\s)!\\w+"
}
- Prepare TrackingCharacter: Define the
getTrackingCharacter()method to return '!' as the shortcut tracking character inShortcutFormatterclass.
- Swift
override func getTrackingCharacter() -> Character {
return "!"
}
- Override Search Method: Override the
search()method to search for shortcuts based on the entered query.
- Swift
override func search(string: String, suggestedItems: (([CometChatUIKitSwift.SuggestionItem]) -> ())? = nil) {
if messageShortcuts.isEmpty == true {
CometChat.callExtension(slug: "message-shortcuts", type: .get, endPoint: "v1/fetch", body: nil) { [weak self] extensionResponseData in
guard let this = self else { return }
if let shotCutData = extensionResponseData?["shortcuts"] as? [String: String] {
this.messageShortcuts = shotCutData
var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]()
this.messageShortcuts.forEach({ (key, value) in
if key.hasPrefix(string) {
suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value))
}
})
suggestedItems?(suggestedItemsList)
}
} onError: { error in
print("Error occured while fetcing shot cuts: \(error?.errorDescription)")
}
} else {
var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]()
messageShortcuts.forEach({ (key, value) in
if key.hasPrefix(string) {
suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value))
}
})
suggestedItems?(suggestedItemsList)
}
}
- Handle prepareMessageString: Implement the
prepareMessageString()method to convert the base chat message into an attributed string for display in theShortcutFormatterclass.
- Swift
override func prepareMessageString(baseMessage: BaseMessage, regexString: String, alignment: MessageBubbleAlignment = .left, formattingType: FormattingType) -> NSAttributedString {
let message = (baseMessage as? TextMessage)?.text ?? ""
return NSAttributedString(string: message)
}
- Handle onTextTapped: Override the
onTextTapped()method if needed.
- Swift
override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) {
// Your code here
}
- Below is an example of how a
ShortcutFormatterSwift file might look:
ShortcutFormatter.swift
import Foundation
import CometChatSDK
import CometChatUIKitSwift
class ShortcutFormatter: CometChatTextFormatter {
private var messageShortcuts: [String: String] = [String: String]()
private var shortcuts: [CometChatUIKitSwift.SuggestionItem] = []
override init(trackingCharacter: Character) {
super.init(trackingCharacter: "!")
}
override func getRegex() -> String {
return "(^|\\s)!\\w+"
}
override func getTrackingCharacter() -> Character {
return "!"
}
override func search(string: String, suggestedItems: (([CometChatUIKitSwift.SuggestionItem]) -> ())? = nil) {
if messageShortcuts.isEmpty == true {
CometChat.callExtension(slug: "message-shortcuts", type: .get, endPoint: "v1/fetch", body: nil) { [weak self] extensionResponseData in
guard let this = self else { return }
if let shotCutData = extensionResponseData?["shortcuts"] as? [String: String] {
this.messageShortcuts = shotCutData
var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]()
this.messageShortcuts.forEach({ (key, value) in
if key.hasPrefix(string) {
suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value))
}
})
suggestedItems?(suggestedItemsList)
}
} onError: { error in
print("Error occured while fetcing shot cuts: \(error?.errorDescription)")
}
} else {
var suggestedItemsList = [CometChatUIKitSwift.SuggestionItem]()
messageShortcuts.forEach({ (key, value) in
if key.hasPrefix(string) {
suggestedItemsList.append(CometChatUIKitSwift.SuggestionItem(id: key, name: value, visibleText: value))
}
})
suggestedItems?(suggestedItemsList)
}
}
override func prepareMessageString(baseMessage: BaseMessage, regexString: String, alignment: MessageBubbleAlignment = .left, formattingType: FormattingType) -> NSAttributedString {
let message = (baseMessage as? TextMessage)?.text ?? ""
return NSAttributedString(string: message)
}
override func onTextTapped(baseMessage: BaseMessage, tappedText: String, controller: UIViewController?) {
// Your code here
}
}
Usage
- Initialization: Initialize an instance of
ShortCutFormatterin your application.
- Swift
let shortcutFormatter = ShortcutFormatter(trackingCharacter: "!")
- Integration: Integrating the
ShortCutFormatterinto your CometChat application involves incorporating it within your project to handle message shortcuts. If you're utilizing the CometChatConversationsWithMessages component, you can seamlessly integrate the ShortCutFormatter to manage shortcut functionalities within your application.
- Your final integration code should look like this:
- Swift
let shortcutFormatter = ShortcutFormatter(trackingCharacter: "!")
let messageComposerConfiguration = MessageComposerConfiguration()
.set(textFormatter: [shortcutFormatter])
let messageListConfiguration = MessageListConfiguration()
.set(textFormatter: [shortcutFormatter])
let messageConfiguration = MessagesConfiguration()
.set(messageComposerConfiguration: messageComposerConfiguration)
.set(messageListConfiguration: messageListConfiguration)
let cometChatConversationsWithMessages = CometChatConversationsWithMessages()
.set(messagesConfiguration: messageConfiguration)
tip
Ensure to pass and present cometChatConversationsWithMessages. If a navigation controller is already in use, utilize the pushViewController function instead of directly presenting the view controller.
Example
