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

正如标题所说,现在我可以用
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
    
已邀请:
使用
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];
    
这是@omz答案的快速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
        }
    }
}
    

要回复问题请先登录注册