一尘不染

重用安全范围书签

swift

在我的应用程序中,我想使用安全范围内的书签访问本地文件目录。

如《应用程序沙箱设计指南》中所述,我将用户指定的文件夹(NSOpenPanel)存储在安全范围内的书签(作为NSData)中。

但是,我发现URLByResolvingBookmarkData在Swift中不再可用。我不知道在重新启动应用程序后如何访问URL并将权限授予先前选择的目录。有任何想法吗?

/// 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")
        }
    }
}

阅读 301

收藏
2020-07-07

共1个答案

一尘不染

我用 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)")
        }
    }
}
2020-07-07