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

27

正如标题所述,现在我可以使用initWithHTML:documentAttributes:将HTML简单地转换为NSAttributedString,但我想在这里做的是相反的操作。 有没有第三方库可以实现这一点?

   @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

2
标题询问如何将HTML转换为NSAttributeString,而问题则相反。 - Eimantas
你发布的代码到底有什么问题?它应该可以工作。 - omz
2个回答

45

使用带有文档类型属性(NSDocumentTypeDocumentAttribute)设置为HTML(NSHTMLTextDocumentType)的dataFromRange:documentAttributes:方法:

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];

如果文本包含链接,则不会为链接创建超链接。 - Balazs Nemeth
12
我只需要HTML中的加粗、斜体、下划线和删除线标签,但是将NSAttributedString转换为HTML会输出大量css来实现这一点。有没有其他简单的方法来解决这个问题? - ilight
@ilight。你找到获取加粗、斜体和下划线HTML标签的解决方案了吗? - Uma Madhavi
1
有人找到了一种方法来获得更干净/自定义的HTML,从 NSAttributedString.DocumentType.html 转换中吗? - Clifton Labrum
@Crashalot 我正在使用 SwiftyMarkdown: https://github.com/SimonFairbairn/SwiftyMarkdown。我稍微修改了一下以满足我的需求,但它运行得非常好。 - Clifton Labrum
显示剩余4条评论

12

这是对@omz回答的Swift 4转换,希望对来到这里的任何人有所帮助。

extension NSAttributedString {
    var attributedString2Html: String? {
        do {
            let htmlData = try self.data(from: NSRange(location: 0, length: self.length), documentAttributes:[.documentType: NSAttributedString.DocumentType.html]);
            return String.init(data: htmlData, encoding: String.Encoding.utf8)
        } catch {
            print("error:", error)
            return nil
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接