如何将NSAttributedString转换为HTML字符串?

前端之家收集整理的这篇文章主要介绍了如何将NSAttributedString转换为HTML字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
正如标题所示,现在我可以使用initWithHTML简单地将HTML转换为NSAttributedString: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:将文档类型属性(NSDocumentTypeDocumentAttribute)设置为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];

猜你在找的HTML相关文章