I'm trying to convert HTML formatted text into an attributed string, and insert it into a SwiftUI view.
Firstly I have a String extension that converts the HTML string to NSAttributedString:
extension String {
func convertHtml() -> NSAttributedString {
guard let data = data(using: .utf8) else { return NSAttributedString() }
if let attributedString = try? NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html], documentAttributes: nil) {
return attributedString
} else {
return NSAttributedString()
}
}
}
Then I have created a HTMLLabel view:
struct HTMLLabel: UIViewRepresentable {
let html: String
func makeUIView(context: UIViewRepresentableContext<Self>) -> UILabel {
let label = UILabel()
label.attributedText = html.convertHtml()
return label
}
func updateUIView(_ uiView: UILabel, context: UIViewRepresentableContext<Self>) {}
}
Then I insert a test into my SwiftUI view:
HTMLLabel(html: "<html><body><b>Hello</b> <i>World</i></body></html>")
The code crashes each time on if let attributedString = try? ... with EXC_BAD_INSTRUCTION. I made a test in an empty storyboard project like this:
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let label = UILabel(frame: CGRect(x: 50, y: 50, width: 320, height: 50))
label.attributedText = "<html><body><b>Hello</b> <i>World</i></body></html>".convertHtml()
view.addSubview(label)
}
}
That code executes without any issues. Why doesn't the code work in a SwiftUI context?