I've developed a document based iOS app using the UIDocumentBrowserViewController
(its a game). On startup of the app I want to reopen the last used UIDocument
automatically. For that I store the url string of the created or opened UIDocument
in the user defaults and try to open that on viewDidLoad
of my DocumentBrowserViewController
. That works fine for documents on local storage but fails on iCloud (or some other foreign) stored documents.
The url string for a locally stored document looks like this:
/private/var/mobile/Containers/Data/Application/F4AF5E0B-C261-47F5-95ED-0B8A1DFEEDE6/Documents/Emsave.emp
The same document on some cloud service has this url string:
/private/var/mobile/Containers/Shared/AppGroup/83CB33FC-5A87-404F-BFB9-8F2910A2192E/File Provider Storage/485172592867551584/Emsave.emp
The viewDidLoad of my DocumentBrowserViewController:
override func viewDidLoad() {
super.viewDidLoad()
delegate = self
allowsDocumentCreation = true
allowsPickingMultipleItems = false
// Do any additional setup after loading the view, typically from a nib.
// did we already open a game before?
if let url = UserDefaults.standard.string(forKey: DocumentBrowserViewController.lastGameKey) {
print("last opened game: \(url)")
if FileManager.default.fileExists(atPath: url) { // and is the game still existing?
presentDocument(at: URL(fileURLWithPath: url)) // open it
}
}
}
The test FileManager.default.fileExists(atPath: url) seems to return always false if the url string specifies a document stored on a cloud service although its there.
You shouldn't hold onto a url you get from the DocumentPicker or the DocumentBrowser, as the file might have moved, been renamed while your app was off.
You should save a bookmark from the url, and recreate the url from the bookmark next time you need it.
Have a look at this section : Bookmarks and Security Scope in https://developer.apple.com/documentation/foundation/nsurl?language=objc