startAccessingSecurityScopedResource() return always false

2.9k views Asked by At

When I try to import a file to my server from iCloud Drive or Dropbox, startAccessingSecurityScopedResource() return false only device but return true when I testing in simulator (Xcode 8, Swift 2.3, minimum target 8.0).

This is my code:

{
        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()
        }
    }

}
1

There are 1 answers

1
apouche On

startAccessingSecurityScopedResource doesn't have to return true it just needs to be paired with stopAccessingSecurityScopedResource().

If it returns false you can still use a NSFileCoordinator to access the resource.

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