Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

reusing security scoped bookmark

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")
        }
    }
}
like image 279
Willjay Avatar asked Mar 08 '16 07:03

Willjay


1 Answers

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)")
        }
    }
}
like image 148
Willjay Avatar answered Sep 20 '22 16:09

Willjay