How to open programmatically a document in a NSDocument macOS app?

Viewed 2852

I'm new to macOS programming and I created a NSDocument app project to learn this architecture.

All works correctly, I can create a document, save it, and open one from Finder using standard UI controls.

I'm trying to save and open a document programmatically. I implemented these two actions. Saving works fine, but read don't work. Edit: I mean that the document window is not shown.

I would be very grateful if somebody could tell me what I'm doing wrong.

// this seems to work because the document is created and I can open it with drag and drop over the app
@IBAction func saveButtonPressed(_ sender: Any) {
    let directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first // or .applicationSupportDirectory

    let docURL = URL(string:"MyFile.docuExperiments", relativeTo:directoryURL)

    if (try? document.write(to: docURL!, ofType: "com.myCompany.docuExperiments")) != nil {
    } else {
        print("An error occured")
    }
}

// the document window is not shown
@IBAction func loadButtonPressed(_ sender: Any) {
    let directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first // or .applicationSupportDirectory

    let docURL = URL(string:"MyFile.docuExperiments", relativeTo:directoryURL)

    if (try? document.read(from: docURL!, ofType: "com.myCompany.docuExperiments")) != nil {
    } else {
        print("An error occured")
    }
}
2 Answers
Related