如标题所示,现在我可以使用NSAttributedString简单地将HTML转换为initWithHTML:documentAttributes:,但是我在这里要做的是反向操作。
有没有第三方库来实现这一目标?

   @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

最佳答案

在文档类型属性(dataFromRange:documentAttributes:)设置为HTML(NSDocumentTypeDocumentAttribute)的情况下使用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];

10-08 05:27