本文介绍了重用安全范围的书签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在我的应用中,我想使用具有安全范围的书签访问本地文件目录.
如应用程序沙箱设计指南所述,我将用户指定的文件夹(NSOpenPanel)存储在安全范围内的书签中(作为NSData).
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).
但是,我发现 URLByResolvingBookmarkData 在Swift中不再可用.我不知道在重新启动应用程序后如何访问URL并将权限授予先前选择的目录.有什么想法吗?
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")
}
}
}
推荐答案
我用 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)")
}
}
}
这篇关于重用安全范围的书签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!