URL when using ReferenceFileDocument

Hello,

I'm trying to rewrite a NSDocument app using SwiftUI. The file on disk is practically a renamed Zip (files are pretty large).

Using NSDocument it is easy cause I can get an URL and then read/write from/to that URL.

Using ReferenceFileDocument apparently this is not possible cause I'm forced to use FileWrapper for reading/writing and I cannot load the whole file into memory cause it would be too big.

Are there any solutions to use URLs with ReferenceFileDocument?

Thanks,

Giacomo

Did you ever find a solution to this?

Not really. I managed to obtain the url of the file with the following trick. I can try to find something similar to write the file back, but I'm afraid it might be unstable or unpredictable.

import ObjectiveC

// Declare a global var to produce a unique address as the assoc object handle
private var AssociatedObjectHandle: UInt8 = 0

extension FileWrapper {

    var fileURL: URL? {
        get {
            return objc_getAssociatedObject(self, &AssociatedObjectHandle) as? URL
        }
        set {
            objc_setAssociatedObject(self, &AssociatedObjectHandle, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    @objc convenience init(trick url: URL, options: ReadingOptions) throws {
        try self.init(trick: url, options: options)
        self.fileURL = url
    }

}



struct Trick {

    static func execute() {
        let aClass: AnyClass = FileWrapper.self
        let originalMethod = class_getInstanceMethod(aClass, #selector(FileWrapper.init(url:options:)))
        let swizzledMethod = class_getInstanceMethod(aClass, #selector(FileWrapper.init(trick:options:)))
        guard let originalMethod = originalMethod, let swizzledMethod = swizzledMethod else {
            return
        }
        method_exchangeImplementations(originalMethod, swizzledMethod)
    }

}
URL when using ReferenceFileDocument
 
 
Q