When a customer sends a message from a client app that includes a link, Link preview enables to provide a preview text or a thumbnail image of the URL. In this way, a sender and a receiver of the message can be aware of what they're going to see before they open the link.
To provide a link preview by updating a message, every user message sent from a client app should be checked if it includes any URLs through the detector.
Implement the code to parse the HTML source of a URL in a customer's message and extract the OpenGraph metadata of the URL. Then, set the extracted OG metadata as a JSON object and stringify the object to pass it as an argument to a data property in the UserMessageUpdateParams class which is used as a parameter in the GroupChannel updateUserMessage(messageId:params:data:completionHandler:) method.
ticket.channel?.sendUserMessage(TEXT, completionHandler: { (userMessage, error) in
guard let userMessage = userMessage, error == nil else {
// Handle error.
}
let detector = try? NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let match = detector?.firstMatch(in: userMessage.message, options: [], range: NSMakeRange(0, userMessage.message.count))
guard let url = match?.url else { // No matching URL
return
}
URLSession().dataTask(with: url) { (data, response, error) in
guard error == nil, let data = data else {
// Handle error.
}
guard let httpResponse = response as? HTTPURLResponse,
let contentType = httpResponse.allHeaderFields["Content-Type"] as? String,
contentType.contains("text/html") else { return }
let htmlBody = String(data: data, encoding: .utf8)
// Extract ogTitle, ogImage, ogUrl, ogSiteName, ogDescription from htmlBody.
// Refer to Open Graph Protocol(https://ogp.me/), and other open source implementations of OG tag parsing for further details.
let urlPreview = ["type": "SENDBIRD_DESK_URL_PREVIEW",
"body": [
"title": ogTitle,
"image": ogImage,
"url": ogUrl,
"site_name": ogSiteName,
"description": ogDescription
]
] as [String: Any]
// Stringified JSON object
let jsonData = try? JSONSerialization.data(withJSONObject: urlPreview, options: [])
let params = UserMessageUpdateParams()
params.message = userMessage.message
params.data = jsonData?.base64EncodedString()
params.customType = "SENDBIRD_DESK_RICH_MESSAGE"
ticket.channel?.update(messageId: userMessage.messageId, params: params, completionHandler: { (userMessage, error) in
guard error == nil else {
// Handle error.
}
...
// Pass the OG metadata to the update(messageId:params:completionHandler:) method in GroupChannel.
})
}
})
Note: There are various methods to extract OG metadata from the HTML body. You can refer to our GitHub repository for the method we're using.
A sender can add a link preview to the original message through update(messageId:params:completionHandler:) in GroupChannel. Then the channel(_:didUpdate:) delegate method in BaseChannelDelegate will be called for the receiver with a preview of the link on the app or web.