I am currently working on extracting HTML text that includes a YouTube video. In order to showcase this video, I have implemented a preview image.
The original text is as follows:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>\n<p><iframe loading=\"lazy\" title=\"Forza Horizon 5 : RTX 4090 24GB ( 8K Maximum Settings RTX ON / DLSS ON )\" width=\"500\" height=\"281\" src=\"https://www.youtube.com/embed/NcHyE_N1QDI?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" allowfullscreen></iframe></p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
After formatting, it appears like this:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p>\n<p><a href='https://www.youtube.com/watch?v=NcHyE_N1QDI'><img src=\"https://img.youtube.com/vi/NcHyE_N1QDI/maxresdefault.jpg\" alt=\"\" width=\"393.0\"/></a></p>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
Next, I utilize NSMutableAttributedString and set a new value for the UITextView's attributedText property.
The query pertains to how one can superimpose an image with a play button on top of the preview image to make it evident to users that this is a video. My assumption is that CSS can achieve this, but I am unsure about the correct way to integrate it into the code.
Here is my implementation:
private func formatStringWithYTVideo(text: String, with width: Float) -> String {
let iframeTexts = matches(for: ".*iframe.*", in: text)
var newText = text
if !iframeTexts.isEmpty {
for iframeText in iframeTexts {
let iframeId = matches(for: "((?<=(v|V)/)|(?<=be/)|(?<=(\\?|\\&)v=)|(?<=embed/))([\\w-]++)", in: iframeText);
if !iframeId.isEmpty {
let htmlString = """
<p><a href='https://www.youtube.com/watch?v=\(iframeId[0])'><img src="https://img.youtube.com/vi/\(iframeId[0])/maxresdefault.jpg" alt="" width="\(width)"/></a></p>
"""
newText = newText.replacingOccurrences(of: iframeText, with: htmlString)
}
}
}
return newText
}