如何将NSAttributedString转换为HTML字符串?
发布时间:2020-12-14 21:45:33 所属栏目:资源 来源:网络整理
导读:正如标题所示,现在我可以使用initWithHTML简单地将HTML转换为NSAttributedString:documentAttributes:但是我想在这里做的是相反的。 有没有第三方图书馆来实现呢? @implementation NSAttributedString(HTML)-(NSString *)htmlForAttributedString{ NSArr
正如标题所示,现在我可以使用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]; (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |