我正在开发一个OS X 10.9的应用程序,使用
swift,沙盒.
该应用程序需要访问sqlite数据库文件.我让用户用NSOpenPanel选择/打开一个文件.然后,我使用NSUserDefaults保存文件路径供以后使用.
我想每次再次启动应用程序时自动打开此文件.我从NSUserDefault获取存储的路径,但是当我用这个路径打开文件时,我收到一个错误,说我没有权限访问该文件.
(它没有沙盒工作)
它看起来像书签是我的问题的解决方案.
是否有一个很好的教程如何使用swift的书签与osx应用程序?
还有其他建议吗?
这是我的回答,我刚刚在
http://swiftrien.blogspot.com/2015/07/persisting-file-access-rights-between.html的一些帮助下在Swift 3中工作
原文链接:https://www.f2er.com/swift/318629.htmlimport Foundation import Cocoa var bookmarks = [URL: Data]() func bookmarkPath() -> String { var url = app.applicationDocumentsDirectory url = url.appendingPathComponent("Bookmarks.dict") return url.path } func loadBookmarks() { let path = bookmarkPath() bookmarks = NSKeyedUnarchiver.unarchiveObject(withFile: path) as! [URL: Data] for bookmark in bookmarks { restoreBookmark(bookmark) } } func saveBookmarks() { let path = bookmarkPath() NSKeyedArchiver.archiveRootObject(bookmarks,toFile: path) } func storeBookmark(url: URL) { do { let data = try url.bookmarkData(options: NSURL.BookmarkCreationOptions.withSecurityScope,includingResourceValuesForKeys: nil,relativeTo: nil) bookmarks[url] = data } catch { Swift.print ("Error storing bookmarks") } } func restoreBookmark(_ bookmark: (key: URL,value: Data)) { let restoredUrl: URL? var isStale = false Swift.print ("Restoring \(bookmark.key)") do { restoredUrl = try URL.init(resolvingBookmarkData: bookmark.value,options: NSURL.BookmarkResolutionOptions.withSecurityScope,relativeTo: nil,bookmarkDataIsStale: &isStale) } catch { Swift.print ("Error restoring bookmarks") restoredUrl = nil } if let url = restoredUrl { if isStale { Swift.print ("URL is stale") } else { if !url.startAccessingSecurityScopedResource() { Swift.print ("Couldn't access: \(url.path)") } } } } func allowFolder() -> URL? { let openPanel = NSOpenPanel() openPanel.allowsMultipleSelection = false openPanel.canChooseDirectories = true openPanel.canCreateDirectories = true openPanel.canChooseFiles = false openPanel.begin { (result) -> Void in if result == NSFileHandlingPanelOKButton { let url = openPanel.url storeBookmark(url: url!) } } return openPanel.url }
要使用此代码,您必须先调用NSOpenPanel,以便用户可以选择允许您访问的文件夹. NSOpenPanel必须存储为书签并保存到磁盘.
let url = allowFolder() saveBookmarks()
重新启动应用程序时,您必须调用
loadBookmarks()