I have tried everything... Many articles and stackoverflow posts but I just can't seem to get it right. Scenario: I get back html code from a web service, very simple example is:
"<b>TEST</b>"
I convert this string to attributedString like this:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
}
And then I display it like this:
self.textView.attributedText = htmlTextFromWebService.htmlToAttributedString
Perfect, my UITextView displays "TEST" as bold.
Now the problem: I am trying to send it back but the bold is gone. Here's how I'm doing that:
let attrString = NSAttributedString(string: self.textView.text)
var resultHtmlText = ""
do {
let r = NSRange(location: 0, length: attrString.length)
let att = [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType]
let data = try attrString.data(from: r, documentAttributes: att)
if let h = String(data: data, encoding: .utf8) {
resultHtmlText = h
}
} catch {
print("FAILED TO CONVERT TO HTML")
}
resultHtmlText is now:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="Content-Style-Type" content="text/css">
<title></title>
<meta name="Generator" content="Cocoa HTML Writer">
<style type="text/css">
p.p1 {margin: 0.0px 0.0px 0.0px 0.0px}
span.s1 {font-family: 'Helvetica'; font-weight: normal; font-style: normal; font-size: 12.00pt}
</style>
</head>
<body>
<p class="p1"><span class="s1">TEST</span></p>
</body>
</html>
But the web service cannot read this and plus, the bold tag is gone! So ultimately, how can I get resultHtmlText to be this:
"<b>TEST</b>"
I just want simple html tags as my result to send to the web service!
Thanks.