Document Controller search handling of non file: URLs

44 Views Asked by At

Global documents with a custom URL scheme?

I have a need to cache info via a URL, with a custom scheme - non file:; to allow user access, and otherwise treat such URLs as global so any access via its URL sees the same data. It's just a fancy way to access user defaults.

I'm relying on a document controller's document(url:) to find such URL if its document exits - previously opened.

And yet it doesn't?

Consider this in app's did finish launching:

do {
    let ibm = URL.init(string: "https://www.ibm.com")!
    let doc = try docController.makeDocument(withContentsOf: ibm, ofType: "myType")
    assert((doc == docController.document(for: ibm)), "created document is not found?")
} catch let error {
    NSApp.presentError(error)
}

The assert fires!

So I pause and try to figure what I'm doing wrong.

Essentially I'm trying to support non-file: info, in a flat namespace, to provide consistent access and content.

1

There are 1 best solutions below

0
On

Probably not an answer - why such URL schemes aren't being found but a working solution is to cache anything, front the search method with such a cache, but doing so creates a maintenance issue:

@objc dynamic var docCache = [URL:NSDocument]()
override var documents: [NSDocument] {
    let  appDocuments = Array(Set([Array(docCache.values),super.documents].reduce([], +)))
    
    return appDocuments
}
override func document(for url: URL) -> NSDocument? {
    if let document = super.document(for: url) {
        docCache[url] = document
        return document
    }
    else
    if let document = docCache[url] {
        return document
    }
    else
    {
        return nil
    }
}

Enjoy.