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

前端之家收集整理的这篇文章主要介绍了如何将NSAttributedString转换为HTML字符串?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
正如标题所示,现在我可以使用initWithHTML简单地将HTML转换为NSAttributedString:documentAttributes:但是我想在这里做的是相反的。
有没有第三方图书馆来实现呢?
  1. @implementation NSAttributedString(HTML)
  2. -(NSString *)htmlForAttributedString{
  3. NSArray * exclude = [NSArray arrayWithObjects:@"doctype",@"html",@"head",@"body",@"xml",nil
  4. ];
  5. NSDictionary * htmlAtt = [NSDictionary
  6. dictionaryWithObjectsAndKeys:NSHTMLTextDocumentType,NSDocumentTypeDocumentAttribute,exclude,NSExcludedElementsDocumentAttribute,nil
  7. ];
  8. NSError * error;
  9. NSData * htmlData = [self dataFromRange:NSMakeRange(0,[self length])
  10. documentAttributes:htmlAtt error:&error
  11. ];
  12. //NSAttributedString * htmlString = [[NSAttributedString alloc]initWithHTML:htmlData documentAttributes:&htmlAtt];
  13. NSString * htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
  14. return htmlString;
  15. }
  16. @end

解决方法

使用dataFromRange:documentAttributes:将文档类型属性(NSDocumentTypeDocumentAttribute)设置为HTML(NSHTMLTextDocumentType):
  1. NSAttributedString *s = ...;
  2. NSDictionary *documentAttributes = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
  3. NSData *htmlData = [s dataFromRange:NSMakeRange(0,s.length) documentAttributes:documentAttributes error:NULL];
  4. NSString *htmlString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];

猜你在找的HTML相关文章