I am trying to save the content of a NSTextView item containing text, images, and different formatting as bold, italic, different font size and color. Currently I am only able to save the raw text but not the images nor the formatting.
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")
}
I tried saving the file as rtf or rtfd but it's only saving the raw content.
Edit : I found how to save and load the rich text but still now way to save the images pasted in the text view. If I make a file .rtfd with an image it loads so the problem is clearly somewhere in the save function. Here is my new code to save :
// 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)")
}