I have faced similar use cases and was always a pain. So, I can think mainly of two options:
- Using the available native APIs.
You convert the HTML to an attributed string like this (see Convert HTML to NSAttributedString in iOS):
let htmlData = NSString(string: details).data(using: String.Encoding.unicode.rawValue)
let options = [NSAttributedString.DocumentReadingOptionKey.documentType:
NSAttributedString.DocumentType.html]
let attributedString = try? NSAttributedString(data: htmlData ?? Data(),
options: options,
documentAttributes: nil)
However, this is slow and when used in combination with UITableViewCell
, may lead to irratic crashes. I suppose the reason is that the native HTML parser has to load WebKit and parse the HTML on a background thread or queue, which does not play well with UITableViewCell rendering pipe line. So, if you go down this path, I suggest to preprocess the HTML (and cache it) and let the UITableViewCell use the attributed strings as a data source.
- Use third party libs.
DTCoreText (https://github.com/Cocoanetics/DTCoreText) seems to solve it, but you should be aware of the licensing.
If you wish just to strip the HTML tags you could use this extension from Google https://chromium.googlesource.com/external/github.com/google/google-toolbox-for-mac/+/refs/heads/master/Foundation/GTMNSString+HTML.h