5

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

}
Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Zept
  • 1,158
  • 1
  • 10
  • 14

1 Answers1

6

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()
}
apouche
  • 9,703
  • 6
  • 40
  • 45
  • 1
    I guess `if (isSecuredURL) { url.stopAccessingSecurityScopedResource() }` should be after catch block, inside the closure – Luzo Jul 18 '18 at 11:31