You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何保存包含格式与图片的NSTextView内容?

NSTextView富文本(含图片)保存异常问题

尝试保存NSTextView中包含文本、图片以及粗体、斜体、不同字号和颜色等格式的内容时,遇到以下问题:

  • 最初仅能保存纯文本,无法保留格式与图片
  • 切换为rtf或rtfd格式保存,仍只能得到纯文本
  • 后续补充:已实现富文本的保存与加载,但粘贴到文本视图中的图片依然无法保存;手动创建的带图片.rtfd文件可正常加载,确定问题出在保存函数中

初始纯文本保存代码

let fileURL = savePath.appendingPathComponent("savedText.txt")
if !fileManager.fileExists(atPath: fileURL.path) {
    do {
        try fileManager.createDirectory(at: savePath, withIntermediateDirectories: true, attributes: nil)
        fileManager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
        print("File created :", fileURL)
    } catch {
        print("Failed to save text to file:", error)
    }
}
do {
    try textView.string.write(to: fileURL, atomically: true, encoding: .utf8)
} catch {
    print("Failed to save the file")
}

改进后的RTFD保存代码

// Save the text to a file whenever it changes
let fileURL = savePath

// if the file doesn't exist make one
if !fileManager.fileExists(atPath: fileURL.path) {
    do {
        try fileManager.createDirectory(at: savePath, withIntermediateDirectories: true, attributes: nil)
        fileManager.createFile(atPath: fileURL.path, contents: nil, attributes: nil)
        print("File created :", fileURL)
    } catch {
        print("Failed to save text to file:", error)
    }
}
// Backup the old file
do {
    try fileManager.copyItem(at: fileURL.appendingPathComponent("savedText.rtfd"), to: fileURL.appendingPathComponent("savedText.rtfd.old"))
} catch {
    print("Error copying file: \(error)")
}

// Save the file
let image = NSImage(named: "MyImage")
let attachment = NSTextAttachment()
attachment.image = image

let attributedString = NSMutableAttributedString(attributedString: textView.attributedString())
let attachmentString = NSAttributedString(attachment: attachment)
attributedString.append(attachmentString)

let fileWrapper = FileWrapper(directoryWithFileWrappers: [:])
let rtfData = attributedString.rtf(from: NSRange(location: 0, length: attributedString.length))
if let rtfData = rtfData {
    fileWrapper.addRegularFile(withContents: rtfData, preferredFilename: "savedText.rtfd")
}

do {
    try fileWrapper.write(to: fileURL, options: .atomic, originalContentsURL: nil)
} catch {
    print("Faild to save the file : \(error)")
}

内容的提问来源于stack exchange,提问作者Nilon123456789

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 06:15:38