正如标题所示,现在我可以使用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];