我有一个NSAttributed字符串(来自HTML)我设置为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;
}
Run Code Online (Sandbox Code Playgroud)
然后我让用户编辑他们想要的内容,然后我想再将其转换为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];
}
Run Code Online (Sandbox Code Playgroud)
它确实返回HTML,但它不是我想要的.一切都被赋予了一个类属性,以及它放在文档顶部的CSS.图像和链接之类的东西甚至不包含在返回的HTML中,可能还有更多问题.
有没有更好的方法来获取HTML NSAttributedString?或者,有没有办法解析NSAttributedString并编写自己的HTML?