0

I have successfully download pdf file from Internet and it is saved in documents directory. The url is as follows of the downloaded file

file:///Users/heetshah/Library/Developer/CoreSimulator/Devices/4BF83AAF-A910-46EB-AE76-91BC6BEED033/data/Containers/Data/Application/B4532805-2842-431F-B16C-C5E448C8366F/Documents/TPAFForm.pdf

I am trying to display it to PDFKit as follows.

let path = URL(fileURLWithPath: pdfUrl!)
if let document = PDFDocument(url: path) {
  pdfView.document = document
  pdfView.displayMode = .singlePageContinuous
  pdfView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
  pdfView.displaysAsBook = true
  pdfView.displayDirection = .vertical
  pdfView.autoScales = true
  pdfView.maxScaleFactor = 4.0
  pdfView.minScaleFactor = pdfView.scaleFactorForSizeToFit
}

I am not getting any error

I have went through bunch of stack overflow posts and it is displaying the same solution as above but it does not work in my case. I also tried following solution but it does not work

if let path = Bundle.main.path(forResource: pdfUrl, ofType: "pdf") {
            let url = URL(fileURLWithPath: path)
            if let pdfDocument = PDFDocument(url: url) {..

Following is my code to download the file

func downloadPDF(pdfUrl: String?,fileName: String,completionHandler:@escaping(String,Bool) -> ()){
        let destinationPath: DownloadRequest.DownloadFileDestination = {
            _,_ in
            let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
            let fileURL = documentsURL.appendingPathComponent("\(fileName).pdf")
            return (fileURL,[.removePreviousFile,.createIntermediateDirectories])
        }

        if let pdfUrl = pdfUrl {
            Alamofire.download(pdfUrl, to: destinationPath).downloadProgress { (progress) in

            }.responseData { (response) in
                switch response.result{
                case .success:
                    if response.destinationURL != nil,let filePath = response.destinationURL?.absoluteString{
                        completionHandler(filePath,true)
                    }
                    break
                case .failure:
                    completionHandler("Something went wrong",false)
                    break
                }
            }
        }
    }

I am using Alamofire to download the file. There constraint for my PDFView are proper as I am able to display an online url pdf in my preview but I need to download the pdf locally first and then display it in my pdf view

  • Possible duplicate of [Open PDF file using swift](https://stackoverflow.com/questions/26883816/open-pdf-file-using-swift) – Rushabh Shah Oct 23 '19 at 11:46
  • @RushabhShah I have went through that post before posting the question. In that post the pdf file is added to the Xcode project which is not relevant in my case. Also it uses WebView in some cases –  Oct 23 '19 at 11:55
  • Hey @RushabhShah, You can use Quick Look Framework. – Rohit Parihar Oct 23 '19 at 13:32
  • So you are saying that your `pdfView` cannot display _any_ PDF? This suggests there is something wrong with the view itself. How did it get into the interface to begin with? Does it have any size? If it has zero size you won't see it. – matt Oct 23 '19 at 13:40
  • How is it not working? – Rudedog Oct 23 '19 at 15:58
  • @matt There is nothing wrong with the size of the preview as I am able to display an online url directly in the pdf –  Oct 24 '19 at 04:20

1 Answers1

4

Since you have not shown sufficient code to debug the problem, here is complete code for doing what you describe, and you can debug your problem by comparing your code to mine:

import UIKit
import PDFKit

class ViewController: UIViewController {

    let pdfurl = URL(string:"https://www.apeth.com/rez/release.pdf")!
    let pdffileurl : URL = {
        let fm = FileManager.default
        let docsurl = try! fm.url(
            for: .documentDirectory, in: .userDomainMask, 
            appropriateFor: nil, create: true)
        return docsurl.appendingPathComponent("mypdf.pdf")
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        let sess = URLSession.shared
        sess.downloadTask(with: self.pdfurl) { (url, resp, err) in
            if let url = url {
                let fm = FileManager.default
                try? fm.removeItem(at: self.pdffileurl)
                try? fm.moveItem(at: url, to: self.pdffileurl)
                DispatchQueue.main.async {
                    self.displayPDF()
                }
            }
        }.resume()
    }

    func displayPDF() {
        let pdfview = PDFView(frame:self.view.bounds)
        pdfview.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        pdfview.autoScales = true
        self.view.addSubview(pdfview)
        let doc = PDFDocument(url: self.pdffileurl)
        pdfview.document = doc
    }

}
matt
  • 515,959
  • 87
  • 875
  • 1,141
  • Thank you for your answer, I have added the code for downloading file in my question, please have a look, I am using Alamofire –  Oct 24 '19 at 04:23
  • you are not downloading the pdf file. I need to download the pdf file to explorer and then display the pdf –  Oct 31 '19 at 08:29
  • 1
    Yes I am downloading it. That is what `sess.downloadTask(with: self.pdfurl)` does. – matt Oct 31 '19 at 09:55