How do you write a completion handler for openDocument(withContentsOf: in Swift 3?

I'm new to Swift. I was wondering how to make a completion handler for openDocument(withContentsOf:display:completionHandler:)


I implemented a part of the code but now I can't figure out how to complete it.


        let documentController = NSDocumentController.shared()
        let directoryURL = FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first
        let docURL = URL(string:"MyFile.docutest", relativeTo:directoryURL)
        documentController.openDocument(withContentsOf: docURL!, display: true, completionHandler: <(NSDocument?, Bool, Error?) -> Void>)

What about this:

documentController.openDocument(withContentsOf: docURL, display: true) {
    (document, documentWasAlreadyOpen, error) in
    if let error = error
    {
      
    }
    else
    {
        if documentWasAlreadyOpen
        {
          
        }
        else
        {
          
        }
    }
}


Dirk

There isn't much that the completion handler needs to do. If there is an error, it should probably display a NSAlert or something like that. That's about it, in most cases.


The point of the completion handler is that this is an asynchronous open. If your code needs to do something app-specific when the document opens, you can't wait for the method call to finish, but you can put code in the completion handler (for the non-error case, I mean).


Other than that, there's no need for the completion handler to do anything.


Note: According to the way the documentation is written:


developer.apple.com/reference/appkit/nsdocumentcontroller/1514992-opendocument


the correct way to know if the method failed is to check whether the "document" parameter is nil, not to check that "error" is non-nil. I suspect that "error" is always nil if the method succeeds, but the documentation doesn't say this explicitly.

Thank you Dirk and QuinceyMorris for your help, it's all clear now!

How do you write a completion handler for openDocument(withContentsOf: in Swift 3?
 
 
Q