9

In my app, I would like to access local file directory with security-scoped bookmark.

As mentioned in App Sandbox Design Guide, I store my user's specified folder (NSOpenPanel) in security-scoped bookmark (as NSData).

However, I find URLByResolvingBookmarkData is no longer available in Swift. I have no idea how can I access the url and grant the permission to the directory I previously chosen after relaunching my app. Any ideas?

/// OpenPanel and set the folderPath
var folderPath: NSURL? {
    didSet {
        do {
            let bookmark = try folderPath?.bookmarkDataWithOptions(.SecurityScopeAllowOnlyReadAccess, includingResourceValuesForKeys: nil, relativeToURL: nil)

        } catch  {
            print("Set bookMark fails")
        }
    }
}
Willjay
  • 6,381
  • 4
  • 33
  • 58
  • 3
    Why do you think that it is not available in Swift? [`init(byResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:)`](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/index.html#//apple_ref/occ/instm/NSURL/initByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error:) – Martin R Mar 08 '16 at 07:57
  • oops... I'm sorry. Thanks a lot. – Willjay Mar 08 '16 at 09:22

1 Answers1

14

I figured it out with NSUserDefaults.

var userDefault = NSUserDefaults.standardUserDefaults()
var folderPath: NSURL? {
    didSet {
        do {
            let bookmark = try folderPath?.bookmarkDataWithOptions(.SecurityScopeAllowOnlyReadAccess, includingResourceValuesForKeys: nil, relativeToURL: nil)
            userDefault.setObject(bookmark, forKey: "bookmark")
        } catch let error as NSError {
            print("Set Bookmark Fails: \(error.description)")
        }
    }
}

func applicationDidFinishLaunching(aNotification: NSNotification) {
    if let bookmarkData = userDefault.objectForKey("bookmark") as? NSData {
        do {
            let url = try NSURL.init(byResolvingBookmarkData: bookmarkData, options: .WithoutUI, relativeToURL: nil, bookmarkDataIsStale: nil)
            url.startAccessingSecurityScopedResource()
        } catch let error as NSError {
            print("Bookmark Access Fails: \(error.description)")
        }
    }
}
Willjay
  • 6,381
  • 4
  • 33
  • 58
  • So it works to use `.securityScopeAllowOnlyReadAccess` to create the bookmark, but then `.withSecurityScope` is *not* needed to resolve it? – pkamb Oct 16 '18 at 01:56
  • @pkamb unbelievable, but it did. I just spent an hour or two trying to load my `.SecurityScopeAllowOnlyReadAccess` bookmark with `.withSecurityScope ` but it was throwing an error about not opening the file. Just stumbled upon this and it works like a charm? – speg May 02 '20 at 04:04