Last active
August 14, 2024 12:34
-
-
Save hashaam/31f51d4044a03473c18a168f4999f063 to your computer and use it in GitHub Desktop.
Strip HTML tags in Swift
extension String {
public func trimHTMLTags() -> String? {
guard let htmlStringData = self.data(using: String.Encoding.utf8) else {
return nil
}
let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
let attributedString = try? NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
return attributedString?.string
}
}
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
Hi,
Thanks for this help. Is there any specific reason behind doing this with "DispatchQueue" ?
I tried to make the code reusable by putting it inside a class, but then it didn't work.
Below is the code :-
The Expected output was complete string without html tags, but it printed the initial value assigned to the class property.
However when I tried below code, it worked!!!