As the title tells,now i can simple convert HTML into NSAttributedString
with initWithHTML:documentAttributes:
, but what i want to do here is reverse. Is there any 3rd party library to achieve this?
@implementation NSAttributedString(HTML) -(NSString *)htmlForAttributedString{ NSArray * exclude = [NSArray arrayWithObjects:@"doctype", @"html", @"head", @"body", @"xml", nil ]; NSDictionary * htmlAtt = [NSDictionary dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType, NSDocumentTypeDocumentAttribute, exclude, NSExcludedElementsDocumentAttribute, nil ]; NSError * error; NSData * htmlData = [self dataFromRange:NSMakeRange(0, [self length]) documentAttributes:htmlAtt error:&error ]; //NSAttributedString * htmlString = [[NSAttributedString alloc]initWithHTML:htmlData documentAttributes:&htmlAtt]; NSString * htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding]; return htmlString; } @end
Creating an Attributed String from MarkdownUse Markdown syntax to initialize an attributed string with text and attributes. Use a Markdown-syntax string to iniitalize an attributed string with standard or custom attributes.
You can convert HTML entities to their equivalent using an extension like this: import UIKit extension String { var decoded: String { let attr = try? NSAttributedString(data: Data(utf8), options: [ . documentType: NSAttributedString.
An NSAttributedString object manages character strings and associated sets of attributes (for example, font and kerning) that apply to individual characters or ranges of characters in the string. An association of characters and their attributes is called an attributed string.
A mutable string with associated attributes (such as visual style, hyperlinks, or accessibility data) for portions of its text.
Use dataFromRange:documentAttributes:
with the document type attribute (NSDocumentTypeDocumentAttribute
) set to HTML (NSHTMLTextDocumentType
):
NSAttributedString *s = ...; NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType}; NSData *htmlData = [s dataFromRange:NSMakeRange(0, s.length) documentAttributes:documentAttributes error:NULL]; NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
This is a swift 4 conversion of @omz answer, hope is useful to anyone landing here
extension NSAttributedString { var attributedString2Html: String? { do { let htmlData = try self.data(from: NSRange(location: 0, length: self.length), documentAttributes:[.documentType: NSAttributedString.DocumentType.html]); return String.init(data: htmlData, encoding: String.Encoding.utf8) } catch { print("error:", error) return nil } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With