iOS NSAttributedString 到 HTML

标签 ios objective-c uitextview nsattributedstring textkit

我为 UITextView 设置了一个 NSAttributed 字符串(来自 HTML)。

- (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,但不是我想要的。一切都被赋予了一个类属性,并将 CSS 放在文档的顶部。图片和链接之类的东西甚至没有包含在返回的 HTML 中,而且可能还有很多问题。

是否有更好的方法从 NSAttributedString 获取 HTML?或者,有没有一种方法可以解析 NSAttributedString 并编写我自己的 HTML?

最佳答案

或许您可以查看该存储库: https://github.com/IdeasOnCanvas/Ashton

有两个有趣的类:

AshtonHTMLReader.h

 - (NSAttributedString *)attributedStringFromHTMLString:(NSString *)htmlString;

作者:

AshtonHTMLWriter.h

- (NSString *)HTMLStringFromAttributedString:(NSAttributedString *)input;

生成的 html 不是很好,但是如果您尝试在 uiwebview 中显示它, 看起来不错。

图像的简单想法: 用 base64 编码并直接将其放在具有正确框架的 < img > 标签中。

虽然丑陋但有效 => 几个月前我已经使用这个过程创建和编辑了一些 html 文件

关于iOS NSAttributedString 到 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309606/

相关文章:

ios - 为什么 UIViewController 在 UINavigationBar 下扩展,而 UITableViewController 没有?

Objective-C 将 '00120' 之类的字符串转换为整数数组

ios - 如果未设置为初始窗口,则自定义 Segue 不起作用

iOS:以编程方式将 TextView 滚动到底部会在文本后创建一个大的空白

iphone - 如何使用 NSUndoManager 支持替换 UITextView 中的文本?

ios - Swift 字符串中的换行符和/或回车符

iphone - 禁止点击背景 UIViewController

iphone - 从iOS Phonegap中的URL下载图像

ios - 如何将包含\u转义字符的JSON解码为UTF8 NSString?

objective-c - 使用 FPS 在 iOS 上测量 CoreGraphics 性能