file access in a sandboxed osx app with swift -
i working on app osx 10.9 swift, sandboxed. app needs access sqlite database file. let user choose/open file nsopenpanel. save file path nsuserdefaults later use.
i want file opened automatically every time when app started again. stored path nsuserdefault, when open file path error, saying have no permission access file. (it working without sandboxing)
it looks bookmark's solution problem.
is there tutorial how use bookmark's swift osx app? other suggestion?
here answer i've got working in swift 3 little http://swiftrien.blogspot.com/2015/07/persisting-file-access-rights-between.html
import 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] bookmark in bookmarks { restorebookmark(bookmark) } } func savebookmarks() { let path = bookmarkpath() nskeyedarchiver.archiverootobject(bookmarks, tofile: path) } func storebookmark(url: url) { { 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)") { 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 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 } to use code must first call nsopenpanel user can select folders give access to. nsopenpanel must stored bookmark , saved disk.
let url = allowfolder() savebookmarks() when restart application must call
loadbookmarks() then app have same level of access did when user selected folder. hope helps someone.
Comments
Post a Comment