0

i am implementing pdf preview in my Swift app so i have decided to use third party library for Preview PDF i am using below library

Please Check Library Here

so first i am download url and store to document directory and than i am displaying it but pdf not previewed below is my code

func downloadFileFromURL(url: String)  {

    if let audioUrl = URL(string: url) {

        let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

        let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
        print(destinationUrl)


        if FileManager.default.fileExists(atPath: destinationUrl.path) {
            print("The file already exists at path")
            print(destinationUrl)
            let document = try! PDFDocument(filePath: destinationUrl.lastPathComponent, password: "")

            self.collectionView.document = document
        } else {
            URLSession.shared.downloadTask(with: audioUrl, completionHandler: { (location, response, error) -> Void in
                guard let location = location, error == nil else { return }
                do {
                    try FileManager.default.moveItem(at: location, to: destinationUrl)
                    print(destinationUrl)
                    let document = try! PDFDocument(filePath: destinationUrl.lastPathComponent, password: "")

                    self.collectionView.document = document
                    print("File moved to documents folder")
                } catch let error as NSError {
                    print(error.localizedDescription)
                }
            }).resume()
        }
    }
}

and inside viewDidLoad() i am implementing below code

downloadFileFromURL(url: "http://housedocs.house.gov/edlabor/AAHCA-BillText-071409.pdf")

but still pdf is not previewed can some tell me its the right way to preview pdf with UXMPdf

or suggest me best pdfviewer for Swift from which i can load pdf from URL

Green
  • 15
  • 7

1 Answers1

0

You have to specify the full path rather than the last path component.

And remove the ! inside a do - catch block.

let document = try PDFDocument(filePath: destinationUrl.path, password: "")

As the password parameter is unused I recommend to use the built-in initializer

let document = try PDFDocument(url: destinationUrl)

vadian
  • 274,689
  • 30
  • 353
  • 361
  • if i put with url than i am getting error `Incorrect argument label in call (have 'url:', expected 'coder:')` – Green Oct 21 '19 at 07:21
  • It seems that the library hides the `url` initializer. So use the first syntax. – vadian Oct 21 '19 at 07:23
  • Did you replace both occurrences of `PDFDocument(filePath:`? Set a breakpoint to check if the document was loaded at all – vadian Oct 21 '19 at 07:27