I am working on a document based app in swift using UIDocumentBrowserViewController
. I would like the app to default to opening the previous file that was used in the last session. When exiting the app I save the file URL in UserDefaults. When I restart the app, UIDocumentBrowserViewController
presents its view. I would like to add in viewDidLoad()
an if-statement that checks if a fileURL
exits in UserDefaults
. If it does I would like to select that file, open it and present it. The simplest approach would seem to be to figure out how to piggyback off of the existing presentDocument(at: documentURL)
methods I am using with UIDocumentBrowserViewController
, or perhaps off of one of the UIDocumentBrowserViewControllerDelegate methods; In the other words I would like to programmatically select a file in UIDocumentBrowserViewController
and present it. However, when I try this the document fails to open, in the UIDocument
method open(completionHandler: )
(i.e. the completion handler reports a failure). I am sure I have the correct fileURL, also the file I am attempting to do this with is in the cloud directory Any Ideas on how this should be implemented?
Asked
Active
Viewed 237 times
1

siege097
- 83
- 7
1 Answers
0
I figured out you have to use a bookmark instead of a URL. The code to create a bookmark and save it to UserDefaults
is as follows:
do {
let bookmark = try (document.fileURL as NSURL).bookmarkData(options: .suitableForBookmarkFile, includingResourceValuesForKeys: nil, relativeTo: nil)
UserDefaults.standard.set(bookmark, forKey: "bookmark")
} catch let error as NSError {
print("Set Bookmark Fails: \(error.description)"
}
and the code to retrieve the bookmark, convert it to a URL, and present the document is as follows:
if let bookmarkData = (UserDefaults.standard.object(forKey: "bookmark") as? NSData) {
do {
let url = try NSURL.init(resolvingBookmarkData: bookmarkData as Data, options: .withoutUI, relativeTo: nil, bookmarkDataIsStale: nil)
url.startAccessingSecurityScopedResource()
presentDocument(at: url as URL)
} catch let error as NSError {
print("Bookmark Access Fails: \(error.description)")
}
}

siege097
- 83
- 7