Hana Jas
Hana Jas

Reputation: 11

View pdf in swift 4

i have tried everything on internet to add a PDFViewer in my app. im working with ios 12. im asking you to help me understand what is the possible ways to add a pdf and a solution that can solve it in a easy way for my low experience with swift coding. thank you

Upvotes: 1

Views: 295

Answers (3)

Pawan Kumar
Pawan Kumar

Reputation: 558

We can use our native UIDocumentInteractionController for the same.

Follow below steps :

Step 1

 var documentInteractionController = UIDocumentInteractionController()

Step 2

 self.documentInteractionController.delegate = self

Step 3

  func openDocument(atURL url: URL, screenTitle: String) {
    self.documentInteractionController.url = url
    self.documentInteractionController.name = screenTitle
    self.documentInteractionController.delegate = self
    self.documentInteractionController.presentPreview(animated: true)
}

Step 4 : Implement UIDocumentInteractionControllerDelegate

extension ViewController: UIDocumentInteractionControllerDelegate  {
// when a document interaction controller needs a view controller for presenting a document preview.

func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
    return self.navigationController ?? UIViewController()
}

}

Some helper methods :

a) View Pdf

  func viewPdf(urlPath: String, screenTitle: String) {
    // open pdf for booking id
    guard let url = urlPath.toUrl else {
        print("Please pass valid url")
        return
    }

    self.downloadPdf(fileURL: url, screenTitle: screenTitle) { localPdf in
        if let url = localPdf {
            DispatchQueue.main.sync {
                self.openDocument(atURL: url, screenTitle: screenTitle)
            }
        }
    }
}

b) function for download file

  // method  for download pdf file
func downloadPdf(fileURL: URL, screenTitle: String, complition: @escaping ((URL?) -> Void)) {
    // Create destination URL
    if let documentsUrl: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first {
        let destinationFileUrl = documentsUrl.appendingPathComponent("\(screenTitle).pdf")

        if FileManager.default.fileExists(atPath: destinationFileUrl.path) {
            try? FileManager.default.removeItem(at: destinationFileUrl)
        }

        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)

        let request = URLRequest(url: fileURL)

        let task = session.downloadTask(with: request) { tempLocalUrl, response, error in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }

                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                    complition(destinationFileUrl)
                } catch let writeError {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }

            } else {
                print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "N/A")")
            }
        }
        task.resume()
    } else {
        complition(nil)
    }
}

Upvotes: 1

Yisus
Yisus

Reputation: 161

If you just need to present the PDF, you could use a WebView from WebKit and pass the data using the mimetype application/pdf.

like this:

        webView.load(data, mimeType: "application/pdf", characterEncodingName: "UTF-8", baseURL: baseURL)

Upvotes: 0

NEEL PATEL
NEEL PATEL

Reputation: 11

here I am Downloading PDF and store on in File And Open That file in Quick Look

Here I am sharing screen enter image description here

Reference link: https://www.hackingwithswift.com/example-code/libraries/how-to-preview-files-using-quick-look-and-qlpreviewcontroller

Upvotes: 0

Related Questions