Read and write permission for user selected folder in Mac OS app?

前端 未结 3 1202
清歌不尽
清歌不尽 2020-12-30 12:12

I am developing MAC OS app which have functionality to create file on the behalf of your. First user select folder for storing file (One time at start of app) and then user

3条回答
  •  隐瞒了意图╮
    2020-12-30 12:53

    I found the best and working answer here - reusing security scoped bookmark

    Super simple, easy to understand and does the job pretty well.

    The solution was :-

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

提交回复
热议问题