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.
Prepare TrackingCharacter: Define the getTrackingCharacter() method to return ’!’ as the shortcut tracking character in ShortcutFormatter class.
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 occurred while fetching shortcuts: \(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 the ShortcutFormatter class.
Initialization: Initialize an instance of ShortCutFormatter in your application.
Swift
let shortcutFormatter = ShortcutFormatter(trackingCharacter: "!")
Integration: Integrating the ShortCutFormatter into your CometChat application involves incorporating it within your project to handle message shortcuts. If you’re utilizing the CometChatMessageComposer 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 cometChatMessageComposer = CometChatMessageComposer()cometChatMessageComposer.set(textFormatter: [shortcutFormatter])
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.