重用安全范围的书签 [英] reusing security scoped bookmark

查看:95
本文介绍了重用安全范围的书签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用中,我想使用具有安全范围的书签访问本地文件目录.

应用程序沙箱设计指南所述,我将用户指定的文件夹(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).

但是,我发现

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

这篇关于重用安全范围的书签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆