2016-12-14 267 views
1

當我嘗試從iCloud Drive或Dropbox將文件導入服務器時,startAccessingSecurityScopedResource()僅返回false設備,但在模擬器(Xcode 8,Swift 2.3,minimum target 8.0)中測試時返回true。startAccessingSecurityScopedResource()return always false

這是我的代碼:

{ 
     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

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