Skip to content

Instantly share code, notes, and snippets.

@hashaam
Last active August 14, 2024 12:34
Show Gist options
  • Save hashaam/31f51d4044a03473c18a168f4999f063 to your computer and use it in GitHub Desktop.
Save hashaam/31f51d4044a03473c18a168f4999f063 to your computer and use it in GitHub Desktop.
Strip HTML tags in Swift
// https://hashaam.com/2017/06/11/strip-html-tags-in-swift/
let htmlString = "LCD Soundsystem was the musical project of producer <a href='http://www.last.fm/music/James+Murphy' class='bbcode_artist'>James Murphy</a>, co-founder of <a href='http://www.last.fm/tag/dance-punk' class='bbcode_tag' rel='tag'>dance-punk</a> label <a href='http://www.last.fm/label/DFA' class='bbcode_label'>DFA</a> Records. Formed in 2001 in New York City, New York, United States, the music of LCD Soundsystem can also be described as a mix of <a href='http://www.last.fm/tag/alternative%20dance' class='bbcode_tag' rel='tag'>alternative dance</a> and <a href='http://www.last.fm/tag/post%20punk' class='bbcode_tag' rel='tag'>post punk</a>, along with elements of <a href='http://www.last.fm/tag/disco' class='bbcode_tag' rel='tag'>disco</a> and other styles. <br />"
let htmlStringData = htmlString.data(using: String.Encoding.utf8)!
let options: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
DispatchQueue.global(qos: .userInitiated).async {
// perform in background thread
let attributedString = try! NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
DispatchQueue.main.async {
// handle text in main thread
let stringWithoutHTMLTags = attributedString.string
}
}
@buraczewskidominik
Copy link

buraczewskidominik commented Aug 14, 2024

The provided solution is easy to use, however, there is some significant downside. If you are working on a big scale project with complex views you might end up getting a warning === AttributeGraph: cycle detected through attribute === and the view would not refresh properly. This was detected to be caused by the legacy API related to NSAttributedString. It is not fixed yet as far as I know. This usually happens when you do some heavy calculations and set up a view model inside the init of the view.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment