How do i convert NSAttributedString into HTML string?

匿名 (未验证) 提交于 2019-12-03 08:36:05

问题:

As the title tells,now i can simple convert HTML into NSAttributedString with initWithHTML:documentAttributes: , but what i want to do here is reverse. Is there any 3rd party library to achieve this?

   @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 

回答1:

Use dataFromRange:documentAttributes: with the document type attribute (NSDocumentTypeDocumentAttribute) set to 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]; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!