I have a UITextView where I\'m managing an NSAttributedString, initially entered as normal via the keyboard. I save the attributed string as HTML, which looks fine. When I
This is not entirely an answer, more an alternative and a comment on the various other answers given, so apologies.
The answers given @KishoreThindaak and @Danomatika are fine if you know what the font sizes should be - but my application has a Mac OS twin which can generate any size text, and therefore had to be general.
The answer given by @k06a works for simple text, but I found that it failed with embedded styles - particularly with multiple styles on a line which itself was embedded in an tag.
After many hours of trying to fix this, I'm afraid I abandoned HTML altogether as the disk format and adopted RTF instead, which works fine, and provides an RTF file that is readable on all platforms. Simple code for getting RTF below...
extension NSAttributedString {
func rtf(encoding: String.Encoding) -> Data? {
let options: [NSAttributedString.DocumentAttributeKey : Any] = [
NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.rtf,
NSAttributedString.DocumentAttributeKey.characterEncoding: encoding.rawValue
]
return try? self.data(from: NSMakeRange(0, self.length), documentAttributes: options)
}
class func from(rtfData data: Data, encoding: String.Encoding) -> NSAttributedString? {
let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.rtf,
NSAttributedString.DocumentReadingOptionKey.characterEncoding: encoding.rawValue
]
return try? NSMutableAttributedString(data: data, options: options, documentAttributes: nil)
}
}