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.
Provide a Link preview
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 parameter in the SBDGroupChannel.update(userMessage, messageText, data, customType, 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: [])
ticket.channel?.update(userMessage, messageText: userMessage.message, data: jsonData?.base64EncodedString(), customType: "SENDBIRD_DESK_RICH_MESSAGE", completionHandler: { (userMessage, error) in
guard error == nil else {
// Handle error.
}
...
// Pass the OG metadata to the SBDGroupChannel.update(userMessage, messageText, data, customType, completionHandler) method.
})
}
})
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.
As a result, the original message is updated with a link preview through the SBDGroupChannel.update() of the SBDChannelDelegate, and a sender and a receiver of the message can see a preview of the link on their app or a web.