I need to save an NSMutableAttributedString
to a file. I set it up as I normally would for an NSString
, but I found that write
doesn't work for attributed text. I changed the file extension to .rtf to see if that would do anything, but it didn't. I also did some research, and I found only two questions that could be helpful. However, this, which had no answers, and this, which had an outdated (Swift 2) answer that I also didn't fully understand. Specifically, this comment gave me some ideas about what to use, but the documentation wasn't helpful to me about how to use it.
In addition, it seems like some have been renamed with changed syntax in Swift 3, which makes it slightly more difficult. In addition, the specific usage and purpose of each are somewhat confusing to me. The other answer gave me a little help, but in the end hasn't helped me enough to solve my issue. The answer is about writing it using NSSavePanel
, which, from what I gather, is based on user input. What I thought would be applicable from this was the part that recommended doing fileWrapperFromRange(range, documentAttributes: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType])
. However, I'm now confused as Swift 3's syntax has changed for it, and at this point I have no idea what I am doing and I'm flying blind. I feel as though this could have promise, but I have absolutely no idea how to apply it or use it, so I took it out. Here is my code so far:
func createFile(text:NSMutableAttributedString) {
let file = "Attributed.rtf"
if let dir : NSString = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first as! NSString {
let path = dir.appendingPathComponent(file);
do {
try text.write(toFile: path,atomically: false, encoding: String.Encoding.utf8.rawValue)//.write is the issue
} catch {
}
}
}
How could I turn this into a document that contains the attributed text in Swift 3? Thanks.
Edit: This ended up working for me:
func createFile(attributedText:NSMutableAttributedString) {
let file = "Attributed.rtf"
if let dir : NSString = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.allDomainsMask, true).first as! NSString {
let path = dir.appendingPathComponent(file);
do {
let stringData = try attributedText.data(from: NSRange(location: 0, length: attributedText.length), documentAttributes: [NSDocumentTypeDocumentAttribute: NSRTFTextDocumentType])
let newStringData = String(data: stringData, encoding: .utf8)
try newStringData?.write(toFile: path, atomically: false, encoding: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
} catch {
}
}
}