1

I need to load an iCloud file when my app first starts up. I want the app to display the last opened file from when the app was closed, and so if the last opened file is an iCloud file, this is where I run into problems.

First of all let me state that if the last opened file is within my Documents Directory and not within iCloud, then I can open it no problem. I can't just store the full url path since my app's sandbox directory can change when the app is reopened, so I append the path of the last opened file relative to the Documents Directory of the last opened file to my documentDirectory path at runtime by doing this:

var myfolder: URL? {
        get {
            do {
                let docsurl = try fileManager.url(for:.documentDirectory,
                                         in: .userDomainMask, appropriateFor: nil, create: false)
                return docsurl
            } catch {
                return nil
            }
        }
    }

and then this

if let lastOpenedFile = UserDefaults.standard.string(forKey: "lastOpenedFile") {
        let lastOpenedFileURL = myfolder!.appendingPathComponent(lastOpenedFile)
        print(lastOpenedFileURL.path)
        if (FileManager.default.fileExists(atPath: lastOpenedFileURL.path)) {
                documentBrowserViewController.presentDocument(at: lastOpenedFileURL)
        }
}

(If this is a bad way of doing it then let me know!)

Now back to the main issue. For an iCloud file, saving the url is a problem but instead of the problem being that the sandbox directory has changed, it is because I don't have access to the url due to what is mentioned here: How to access files in iCloud Drive from within my iOS app? which says

The document picker calls the delegate’s documentPicker:didPickDocumentAtURL: method when the user selects a destination outside your app’s sandbox. The system saves a copy of your document to the specified destination. The document picker provides the copy’s URL to indicate success; however, your app does not have access to the file referred to by this URL.

So my question is how can I load this last opened file if it is an iCloud file? The documentBrowser has access to it, but is that because the user has selected the file on the screen and that I can't simulate this in code for protection reasons? Thank you in advance for any help!

Adam
  • 2,070
  • 1
  • 14
  • 18

1 Answers1

1

The document picker is used to copy files into/out of your app's sandbox and an another.

If the files are stored in the general iCloud Drive and not an app's private iCloud container, you can access them via the Ubiquity Url - https://developer.apple.com/documentation/foundation/filemanager/1411653-url

You can append your relative path to the ubiquity url in a way similar to url(for:.documentDirectory

Морт
  • 1,163
  • 9
  • 18