0

I am creating and saving PDFs generated from UIImage to the device. I am also saving the path of that file in the Core Data. I can retrieve the path and check whether the file is present or not, however when I try to load the PDF in UIWebView, the screen returns blank. I have tried loading the request as well as loading data, but none of the approached has worked. I am applying this code to TableView didSelectRow function, so when user clicks on the cell, a reusable popup appears which will load the PDF. Below is my code.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let selectedDoc = tableView.cellForRow(at: indexPath) as! DisplayMainSavedDataCell

    let document : String = selectedDoc.documentNameLabel.text!

    print(document)

    let path = fetchDocumentURL(documentName: document)

    let urlDoc = URL(fileURLWithPath: path)

    print(urlDoc)

    let request = URLRequest.init(url: urlDoc)

    let sb = UIStoryboard.init(name: "Main", bundle: nil)

    let popup = sb.instantiateViewController(withIdentifier: "pdfPopUp") as! PDFViewController

    popup.webView?.loadRequest(request)

    present(popup, animated: true)

}



func fetchDocumentURL (documentName: String) -> String {

    let docName = documentName

    let fetchRequest : NSFetchRequest<Document> = Document.fetchRequest()

    let predicate = NSPredicate(format: "docName == %@", docName as CVarArg)

    fetchRequest.predicate = predicate

    do {

        let results = try PersistenceService.context.fetch(fetchRequest)

        for result in results as [Document] {

            let path = result.docPath

            return path!

        }

        } catch{

            print("files does not exists or file missing")

            let path = "No path exists"

            return path

    }

    let path = "No path exists"

    return path

}
  • Possible duplicate of [How to Load Local PDF in UIWebView in Swift](https://stackoverflow.com/questions/29682245/how-to-load-local-pdf-in-uiwebview-in-swift) – LoVo Jan 07 '18 at 09:31
  • This solution does not work for me as the pdfURL returns nil because I have saved the PDF under the "MyApp" directory in "Applications" directory. – Ankit Badani Jan 07 '18 at 10:11
  • Have you checked that on this line `popup.webView?.loadRequest(request)` `webView` is non nil? Outlets are not initialized early in a view controller's lifecycle only after `viewDidLoad` is called. It's better to create a `URLRequest` property and load it from `PDFViewController`'s `viewDidLoad`. – beyowulf Jan 07 '18 at 15:05
  • I have tried that and now have URLRequest inside the PDFViewController, now all I get is blank screen. It works for any pdfs copied through bundle resources but doesn't display any PDF through path retrieved from Core Data object. – Ankit Badani Jan 08 '18 at 10:59

0 Answers0