Search code examples
swift4ios11uidocumentbrowservc

iOS11 Swift 4: Storing access rights for URLs retrieved from DocumentBrowserViewController


When using DocumentBrowserViewController to access files from other applications, is it possible to store the access rights to those files?

The concrete issue

Currently, for proof of concept purposes, I printed the url for a file, selected via DocumentBrowserViewController, to the console, hardcoded that url somewhere in my code and try to open that file again. That doesn't work because of: {Error Domain=NSPOSIXErrorDomain Code=1 "Operation not permitted"}}

Now, is there a way to store the access rights?

In a blog post I found something using:

do {
    let data = try sourceURL.bookmarkData(
        options: URL.BookmarkCreationOptions.withSecurityScope,
        includingResourceValuesForKeys: nil,
        relativeTo: nil)
    print(data)
} catch {
    print(error)
}

But withSecurityScope is "unavailable". (To be precise: 'withSecurityScope' has been explicitly marked unavailable here (Foundation.NSURL))

Is there a way to do this kind of stuff?

Regards and thanks in advance :)

Edit

So maybe I was a little hasty with the question, the above code just needs to be adjusted into:

do {
    let data = try sourceURL.bookmarkData(
        options: URL.BookmarkCreationOptions.minimalBookmark,
        includingResourceValuesForKeys: nil,
        relativeTo: nil)
    print(data)
} catch {
    print(error)
}

And this data can then be used somehwat like that:

let url = try URL.init(resolvingBookmarkData: data, bookmarkDataIsStale: &stale)!

:)


Solution

  • You need to create a bookmark from the URL and store that. This is explained towards the 40' mark of this WWDC session: https://developer.apple.com/videos/play/wwdc2018/216 and is also in the Particles sample code published last week.

    Essentially, the snippet above is correct, except that the withSecurityScope flag is useless on iOS (this is automatic). When resolving the URL on launch, you need to startAccessing or use UIDocument, which does this for you.