我有一个从HTML转换而来的NSAttributed
字符串,它被设置为一个UITextView
。
- (void)setHtml:(NSString *)html {
NSData *htmlData = [html dataUsingEncoding:NSUTF8StringEncoding];
// Create the HTML string
NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSError *error = nil;
self.htmlString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];
self.editorView.attributedText = self.htmlString;
}
我允许用户编辑他们想要的内容,然后我希望将其转换回HTML格式,因此我使用:
- (NSString *)getHTML {
NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};
NSData *htmlData = [self.editorView.attributedText dataFromRange:NSMakeRange(0, self.editorView.attributedText.length) documentAttributes:exportParams error:nil];
return [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding];
}
它确实返回HTML,但不是我想要的方式。所有内容都被赋予了一个class属性,并且CSS被放在文档的顶部。像图片和链接这样的内容甚至没有包括在返回的HTML中,可能还有更多问题。
有没有更好的方法从NSAttributedString中获取HTML?或者,我是否可以解析NSAttributedString并编写自己的HTML?