Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

withSecurityScope not available in NSURL.BookmarkCreationOptions

Tags:

xcode

ios

swift

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!

like image 815
lopf Avatar asked Oct 16 '22 12:10

lopf


1 Answers

There are two phases.

  1. 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")
    
  2. 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()
    
like image 127
vadian Avatar answered Nov 15 '22 07:11

vadian