当我尝试从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()
}
}
}
答案 0 :(得分:3)
startAccessingSecurityScopedResource
无需返回true
,只需与stopAccessingSecurityScopedResource()
配对。
如果它返回false
,您仍然可以使用NSFileCoordinator
来访问该资源。
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()
}