将包含NSTextAttachment的NSAttributedText保存为base64编码的RTFD字符串,然后还原不会恢复附件内容

我正在尝试将NSAttributedString保存为RTFD,然后从已保存的RTFD恢复NSAttributedString。 (想法是我最终将RTFD保存在数据库中。)

我的问题是附件内容无法从字符串中恢复。如下所示,您可以看到该字符串确实对附件数据进行了编码。

这是一个复制问题的最小示例:

let originalContents = "foobar".data(using: String.Encoding.utf8)
let originalAttachment = NSTextAttachment(data: originalContents,ofType: "public.text")
let originalString = NSMutableAttributedString(string: "deadbeef")
originalString.append(NSMutableAttributedString(attachment: originalAttachment))
originalString.append(NSMutableAttributedString(string: "deadbeef"))

let savedRtfd = originalString.rtfd(from: NSRange(0..<originalString.length))!

let recoveredString = NSAttributedString(rtfd: savedRtfd,documentAttributes: nil)!
let recoveredAttachments = attachments(from: recoveredString) // See *definition below
let recoveredAttachment = recoveredAttachments[0]

我希望这将返回recoveredAttachment.contents == "foobar",但我得到的是 recoveredAttachement.contents == nil。为什么不还原NSTextAttribute的内容?我在这里想念什么?

谢谢您的帮助!

-jeff

  • 以上attachments(from:NSAttributedString) -> Array<NSTextAttachment>方法的定义:
func attachments(from s: NSAttributedString) -> Array<NSTextAttachment> {
    var attachments: Array<NSTextAttachment> = []
    s.enumerateAttribute(.attachment,in: NSRange(0..<s.length)) {
        value,range,stop in
        guard let a = value else {
            return
        }
        attachments.append(a as! NSTextAttachment)
    }
    return attachments
}
gr364212028 回答:将包含NSTextAttachment的NSAttributedText保存为base64编码的RTFD字符串,然后还原不会恢复附件内容

暂时没有好的解决方案,如果你有好的解决方案,请发邮件至:iooj@foxmail.com
本文链接:https://www.f2er.com/3026032.html

大家都在问