从NSAttributedString到HTML到NSAttributedString颜色降级

时间:2019-07-18 21:41:17

标签: swift cocoa nsattributedstring nscolor

我有一个RTF编辑器,用户可以在其中编辑字体,颜色等。模型将此信息作为NSAttributedString的实例保存在内存中。当我想存储此信息并写入磁盘时,我通过以下函数将属性字符串转换为html:

func attributedStringToHtml(attributedString: NSAttributedString) -> String {
    var ret = ""
    do {
        let htmlData = try attributedString.data(from: NSRange( location: 0, length: attributedString.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.html])
        ret =  String.init(data: htmlData, encoding: String.Encoding.utf8)!
    } catch { print("error:", error) }
    return ret
}

并将数据从磁盘拉回到NSAttributedString的实例中,我使用:

func htmlToAttributedString(htmlString: String) -> NSAttributedString {
    return  NSAttributedString.init(html: htmlString.data(using: String.Encoding.utf8)!, documentAttributes: nil)!
}

通过多次循环遍历这些函数会发生问题,即:

保存->加载->保存->加载->保存->加载。

在每个加载周期之后,所存储的颜色变得越来越深。我相信这与色彩空间的转换有关吗?

在macOS 10.13上不会发生此行为。 将其复制并粘贴到游乐场中,作为发生情况的示例:

import AppKit
import PlaygroundSupport

func htmlToAttributedString(htmlString: String) -> NSAttributedString {
    return  NSAttributedString.init(html: htmlString.data(using: String.Encoding.utf8)!, documentAttributes: nil)!
    }

func attributedStringToHtml(attributedString: NSAttributedString) -> String {
    var ret = ""
    do {
        let htmlData = try attributedString.data(from: NSRange( location: 0, length: attributedString.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.html])
        ret =  String.init(data: htmlData, encoding: String.Encoding.utf8)!
    } catch { 
        print("error:", error) 
    }
    return ret
}

let initialHtmlString = "<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<meta http-equiv=\"Content-Style-Type\" content=\"text/css\">\n<title></title>\n<meta name=\"Generator\" content=\"Cocoa HTML Writer\">\n<meta name=\"CocoaVersion\" content=\"1671.5\">\n<style type=\"text/css\">\np.p1 {margin: 0.0px 0.0px 0.0px 0.0px; text-align: center; line-height: 16.0px; font: 14.0px Helvetica; color: #FF0000; -webkit-text-stroke: #000000}\nspan.s1 {font-kerning: none}\n</style>\n</head>\n<body>\n<p class=\"p1\"><span class=\"s1\">Double-click to edit this text</span></p>\n</body>\n</html>\n"

var attributedString = htmlToAttributedString(htmlString: initialHtmlString)
var backToHtml = attributedStringToHtml(attributedString: attributedString)
var backToAttributedString = htmlToAttributedString(htmlString: backToHtml)
var backToHtmlAgain = attributedStringToHtml(attributedString: backToAttributedString)

print(backToHtmlAgain) // notice the html color value is now f6000b

1 个答案:

答案 0 :(得分:-1)

我可以通过使用NSAttributedString.DocumentType.rtf代替html来解决此问题