I'm developing a macOS application for editing files, but am getting a rather annoying error when trying to use NSDocumentController.shared.makeDocument
to create a new NSDocument
instance from a file URL.
Below is a simple example of how I am calling makeDocument
. The file test.md
exists on disk.
let url = URL(fileURLWithPath: "/Users/me/Desktop/test.md"
do {
let newDocument = try NSDocumentController.shared.makeDocument(withContentsOf: url, ofType: url.pathExtension)
print("Created \(newDocument)")
} catch {
print("Error: \(error)")
}
The problem is that this try
call fails and it reaches the catch
block. The error I get is:
Error: Error Domain=NSCocoaErrorDomain Code=256 "“test.md” could not be handled because MyApp cannot open files in the “md” format." UserInfo={NSLocalizedDescription=“test.md” could not be handled because MyApp cannot open files in the “md” format., NSLocalizedFailureReason= MyApp cannot open files in the “md” format.}
I believe i've correctly set my app's Document Types for markdown files as shown below:
I've tried cleaning the build , removing derived data and also adding an 'Imported UTI' type for markdown files but nothing seems to work.
The strange thing is that via File > Open, I am able to open .md
files, just not programatically via makeDocument
.
makeDocument(withContentsOf:ofType:)
expects a type as second parameter, not an extension. Have a look at typeForContents(of url: URL)
on how to derive the type from an URL.
See Figure 6-3 in https://developer.apple.com/library/archive/documentation/DataManagement/Conceptual/DocBasedAppProgrammingGuideForOSX/AdvancedTopics/AdvancedTopics.html
And as Marek H pointed out in his answer, in the info.plist there should be an UTI (identifier) for the document type.