I am trying to simply save using NSDocument to a rtf. The code works fine but when I try to save to a view controller that isn't the initial child to the window controller it throws an error from a modal saying 'The document “” could not be saved as “”.'
How can I save the file to the Second View Controller?
Window Controller
|
Login View Controller
| |
SidebarViewContoller ViewController1
|
TableViewController 2 Replaces VC1
Save TextView in this VC
I want to be able to write data into My NSDocument from the textView in ViewController2 and save it to the desktop Just like you would for instance in Pages
Here is the code
// Document.swift
class Document: NSDocument {
var text = NSAttributedString()
var documentViewController: DocumentViewController? {
return windowControllers[0].contentViewController as? DocumentViewController
}
override init() {
super.init()
// Add your subclass-specific initialization here.
}
override class var autosavesInPlace: Bool {
return true
}
override func makeWindowControllers() {
// Returns the Storyboard that contains your Document window.
let storyboard = NSStoryboard(name: NSStoryboard.Name("Main"), bundle: nil)
let windowController = storyboard.instantiateController(withIdentifier: NSStoryboard.SceneIdentifier("Document Window Controller")) as! NSWindowController
self.addWindowController(windowController)
}
override func data(ofType typeName: String) throws -> Data {
// Save the text view contents to disk
if let textView = documentViewController?.textView {
let rangeLength = textView.string.count
textView.breakUndoCoalescing()
let textRange = NSRange(location: 0, length: rangeLength)
if let contents = textView.rtf(from: textRange) {
return contents
}
}
throw NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
}
override func read(from data: Data, ofType typeName: String) throws {
if let contents = NSAttributedString(rtf: data, documentAttributes: nil) {
text = contents
}
}
//SecondViewController
override func viewDidAppear() {
let document = self.view.window?.windowController?.document as! Document
textView.textStorage?.setAttributedString(document.text)
}