I'm trying to implement a text editor in iOS. It supports basic styles and is able to embed an image. For testing, I created a .rtfd file in Xcode like this:
Here is part of my code:
// Create a text storage object and add it to the layout manager
self.textStorage = NSTextStorage()
let layoutManager = NSLayoutManager()
let container = NSTextContainer(size: CGSize())
container.widthTracksTextView = true
layoutManager.addTextContainer(container)
textStorage.addLayoutManager(layoutManager)
editorView = UITextView(frame: self.view.bounds, textContainer: container)
editorView.isEditable = true
editorView.isSelectable = true
editorView.isScrollEnabled = true
editorView.delegate = self
// read from rtf file
if let docURL = Bundle.main.url(forResource: "test", withExtension: "rtfd") {
do {
try textStorage?.read(from: docURL, documentAttributes: nil)
print("Read rtfd file")
} catch {
// Could not read menu content.
print("error")
}
}
self.view.addSubview(editorView)
I have no problem to load this rtfd
file and show it in my UITextView
. But when I try to save in the following code, it failed:
guard let rtfData = try? textStorage.data(from: NSMakeRange(0, textStorage.length), documentAttributes: [.documentType: NSAttributedString.DocumentType.rtfd]) else {
print("Failed to convert attributed string to RTFD data")
return
}
// Write the RTF data to a file
let fileURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appending(path: "file.rtfd")
do {
try rtfData.write(to: fileURL)
} catch {
print("Failed to write RTF data to file: \(error)")
}
The file has been saved but can't open it. It's a garbage. But when I changed it to rtf
, there is no issue to save. But the image disappears.
By the way, there is a function called rtfd(from:
in NSTextStorage
. But I can't use it in iOS.
Any suggestion? Thanks.