简体   繁体   English

重用安全范围的书签

[英]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). App Sandbox设计指南中所述 ,我将用户指定的文件夹(NSOpenPanel)存储在安全范围的书签中(作为NSData)。

However, I find URLByResolvingBookmarkData is no longer available in Swift. 但是,我发现Swift中不再提供URLByResolvingBookmarkData I have no idea how can I access the url and grant the permission to the directory I previously chosen after relaunching my app. 我不知道如何在重新启动应用程序后访问该URL并将权限授予我之前选择的目录。 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")
        }
    }
}

I figured it out with NSUserDefaults . 我用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)")
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM