4

[new to swift] I testing this function to export some simple file

    @IBAction func exportFile(delegate: UIDocumentInteractionControllerDelegate) {
        print("export csv")
       let fileName = tmpDir.stringByAppendingPathComponent("myFile.csv")
        let url: NSURL! = NSURL(fileURLWithPath: fileName)

        if url != nil {
            let docController = UIDocumentInteractionController(URL: url)
            docController.UTI = "public.comma-separated-values-text"
            docController.delegate = delegate
            docController.presentPreviewAnimated(true)

        }
}
 // Return the view controller from which the UIDocumentInteractionController will present itself.
    func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController)-> UIViewController {
        return self
    }

But when i clicked the export button i am getting the message

UIDocumentInteractionController delegate must implement documentInteractionControllerViewControllerForPreview: to allow preview

I thought

class ViewController: UIViewController, UIDocumentInteractionControllerDelegate {

Would be sufficient?

I tried Self.documentInteractionControllerViewForPreview(docController)

[edit] turned out i had made the following mistake docController.delegate = self//delegate

alex
  • 4,804
  • 14
  • 51
  • 86

2 Answers2

6

You need to implement following delegate methods. Delegates are the callbacks from the service provider to service consumer to be prepared for the action that is about to occur. On some occasions you must provide details (called data source) in order to utilise the said functionality.

func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController!) -> UIViewController! {
    return self
}

func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController!) -> UIView! {
    return self.view
}

func documentInteractionControllerRectForPreview(controller: UIDocumentInteractionController!) -> CGRect {
    return self.view.frame
}

Read through how delegation works. Also, take a look at your specific case here.

Abhinav
  • 37,684
  • 43
  • 191
  • 309
  • hmm still getting the message, i don't use any data source. Any articles on this subject? – alex Sep 09 '15 at 12:28
4

For Swift 3.0

First extend your class

UIDocumentInteractionControllerDelegate

Then only implement the following method

     func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {

    return self
}

Calling the Pdf Viewer

 func MyViewDocumentsmethod(){

    let controladorDoc = UIDocumentInteractionController(url: PdfUrl! as URL)
    controladorDoc.delegate = self
    controladorDoc.presentPreview(animated: true)



}

This should render the following

enter image description here

Khaledonia
  • 2,054
  • 3
  • 15
  • 33