在我的应用程序中,我想访问带有安全范围书签的本地文件目录. 如 App Sandbox Design Guide中所述,我将用户指定的文件夹(NSOpenPanel)存储在安全范围的书签中(作为NSData). 但是,我发现Swift中不再
如 App Sandbox Design Guide中所述,我将用户指定的文件夹(NSOpenPanel)存储在安全范围的书签中(作为NSData).
但是,我发现Swift中不再提供URLByResolvingBookmarkData.
我不知道如何在重新启动应用程序后访问该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") } } }我用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)") } } }