Wie kann ich umwandeln NSAttributedString in HTML-string?
Wie der Titel sagt,jetzt kann ich einfaches konvertieren von HTML in NSAttributedString
mit initWithHTML:documentAttributes:
, aber was will ich tun, hier ist es Umgekehrt.
Gibt es irgendeine 3rd-party-Bibliothek, dies zu erreichen?
@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
- Der Titel fragt, wie konvertieren von HTML in NSAttributeString, obwohl die Frage nicht Umgekehrt.
- Was genau ist das problem mit dem code, den du gepostet hast? Es sollte funktionieren.
Du musst angemeldet sein, um einen Kommentar abzugeben.
Verwenden
dataFromRange:documentAttributes:
mit dem Dokument-Typ-Attribut (NSDocumentTypeDocumentAttribute
) in HTML festgelegt (NSHTMLTextDocumentType
):NSAttributedString.DocumentType.html
Konvertierung?Dies ist ein swift 4 Konvertierung von @omz Antwort, hoffe, dass ist nützlich, zu jeder Landung hier