4

当我尝试从 iCloud Drive 或 Dropbox 将文件导入我的服务器时, startAccessingSecurityScopedResource()仅返回 false 设备,但在我在模拟器中测试时返回 true(Xcode 8、Swift 2.3、最低目标 8.0)。

这是我的代码:

{
        func showCloudDriveAction(inputBar: NAChatInputBar) {
           let documentmenuPicker = UIDocumentMenuViewController(documentTypes: ["public.data"], inMode: .Import)
           documentmenuPicker.delegate = self
           presentViewController?.presentViewController(documentmenuPicker, animated: true, completion: nil)
       }

}

extension NAChatInputBarPresenter: UIDocumentPickerDelegate, UIDocumentMenuDelegate {

    public func documentMenu(documentMenu: UIDocumentMenuViewController, didPickDocumentPicker documentPicker: UIDocumentPickerViewController) {
        documentPicker.delegate = self
        self.presentViewController?.presentViewController(documentPicker, animated: true, completion: nil)
    }

    public func documentPicker(controller: UIDocumentPickerViewController, didPickDocumentAtURL url: NSURL) {
        if url.startAccessingSecurityScopedResource() {
            guard let path = url.path, data = NSData(contentsOfFile: path) else {
                return
            }
            delegate?.chatInputBarPresenter(data, atUrl: url)
            url.stopAccessingSecurityScopedResource()
        }
    }

}
4

1 回答 1

6

startAccessingSecurityScopedResource不必返回true它只需要与stopAccessingSecurityScopedResource().

如果它返回false,您仍然可以使用 aNSFileCoordinator来访问资源。

let isSecuredURL = url.startAccessingSecurityScopedResource() == true
let coordinator = NSFileCoordinator()
var error: NSError? = nil
coordinator.coordinate(readingItemAt: url, options: [], error: &error) { (url) -> Void in
    do {
        // do something
    } catch (_) {
        // something went wrong
    }
}
if (isSecuredURL) {
    url.stopAccessingSecurityScopedResource()
}
于 2017-07-17T15:44:58.370 回答