gpt4 book ai didi

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

转载 作者:技术小花猫 更新时间:2023-10-29 11:48:40 25 4
gpt4 key购买 nike

如标题所示,现在我可以使用 initWithHTML:documentAttributes: 将 HTML 简单地转换为 NSAttributedString,但我想在这里做的是相反的。是否有任何第 3 方库可以实现此目的?

   @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 - 如何将 NSAttributedString 转换为 HTML 字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5298188/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com