2

Full error message is:

[main] *** Error from FPBookmarkableStringFromDocumentURL, file:///private/var/mobile/Library/Mobile%20Documents/com~apple~CloudDocs/MY_APP/hello.txt -> Error Domain=NSCocoaErrorDomain Code=257 "The file couldn’t be opened because you don’t have permission to view it."

This error is thrown from a SceneDelegate (introduced in iOS 13) when I relaunch my app & attempt to reopen previously opened file (for example when the app was "backgrounded" & the memory freed, so I want to reload the state of the scene). I followed the steps from this WWDC session https://developer.apple.com/videos/play/wwdc2019/212 & the downloaded example source code from https://developer.apple.com/documentation/uikit/app_and_environment/scenes/supporting_multiple_windows_on_ipad

I basically copied their configure(window: UIWindow?, with activity: NSUserActivity) -> Bool function and transformed it to fit my needs. It seems to work, flawlessly, but I'm getting the error.

I'm using the default NSUserActivity technique described in "Adopting Handoff in Document-Based Apps" section of https://developer.apple.com/library/archive/documentation/UserExperience/Conceptual/Handoff/AdoptingHandoff/AdoptingHandoff.html#//apple_ref/doc/uid/TP40014338-CH2-SW17

Here's the body of the configure function:

if activity.activityType == "com.myName.MyApp.openedDocumentUserActivity" {

            if let documentURL = activity.userInfo?[UIDocument.userActivityURLKey] as? URL {

                if let docBrowserVC = window?.rootViewController as? DocumentBrowserViewController {
                    documentURL.startAccessingSecurityScopedResource() // tried this, it returns false
                    docBrowserVC.presentDocument(at: documentURL)
                    return true
                }
            }
        }
        return false

If anyone knows about a workaround, thank you.

Jan Kriz
  • 21
  • 1
  • 2

1 Answers1

3

I had to create bookmark data from the URL and persist that in the NSUserActivity. Using UIDocument.documentURL is not sufficient because it is security-scoped.

For creating the bookmark (no error checking in this snippet):

let userActivity = NSUserActivity(activityType: "com.foobar")
let bookmarkData = try? documentURL.bookmarkData()
userActivity.addUserInfoEntries(from: ["URLBookmarkData": bookmarkData])
scene.userActivity = userActivity

Then for reading:

let bookmarkData = userActivity.userInfo?["URLBookmarkData"] as? Data {
let resolvedURL = try? URL(resolvingBookmarkData: bookmarkData, options: NSURL.BookmarkResolutionOptions(), relativeTo: nil, bookmarkDataIsStale: &bookmarkDataIsStale)
Mark Krenek
  • 4,889
  • 3
  • 25
  • 17