im am trying to save a url as a bookmark to persist access to files on an iphone.
To do this i am calling the bookmarkData
function.
But to prevent errors i have encounterd such as:
Error Domain=NSCocoaErrorDomain Code=260 "The file couldn’t be opened because it doesn’t exist."
I am trying to add the withSecurityScope
option when calling the function.
Although I have found multiple references to this option in the Apple documentation I can't seem to be able to find it when using NSURL.BookmarkCreationOptions.withSecurityScope
. It only says 'withSecurityScope' is unavailable
. I have also looked through the class definition but still no luck.
I hope someone can help me out here. Thanks a lot!
There are two phases.
You have to create the bookmark data from the url after getting permission (for example in NSOpenPanel
) and save it
let data = try url.bookmarkData(options: [.withSecurityScope])
UserDefaults.standard.set(data, forKey: "mySecureURL")
To use it get the data from UserDefaults
and resolve it
guard let data = UserDefaults.standard.data(forKey: "mySecureURL") else { // do some error handling }
var isStale = false
let url = try URL(resolvingBookmarkData: data, options:[.withSecurityScope], bookmarkDataIsStale: &isStale)
if isStale { // create new bookmark data from the current url and save it again described in 1. }
Now you can use url
but you have to wrap it in these two lines
url.startAccessingSecurityScopedResource()
// do something with `url`
url.stopAccessingSecurityScopedResource()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With