-1

i am trying to implement pdf download option once user tap on download option pdf file should be downloaded and get open. I tried following link but its not working Saving PDF Files with Swift in iOS and display them and I tried following code. In response its showing Path I gone through with that path but I didn't find any file.

 @objc func downloadPdfFile(_ sender : UIButton)
    {
        var localDic :NSDictionary!
        localDic = totalSyllabusArray.object(at: sender.tag) as! NSDictionary
        let filepath = localDic["filepath"] as! String
        let pdfURLString:String = FETCH_InMegh_Image_BaseURL + filepath
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first as URL!
        let destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
        //Create URL to the source file you want to download
        let fileURL = URL(string: pdfURLString)
        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)
                } catch (let writeError) {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                }
            } else {
                print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
            }
        }
        task.resume()
    }
kishore
  • 3
  • 6

1 Answers1

0

Hey @kishore Apple recently added PDfKit Framework try this below link.

https://developer.apple.com/documentation/pdfkit

Here what all you need to do is Take One UIView in storyboard to display Pdf files . and in Identity Inspector set class as PDFView. Take outlet like this.

@IBOutlet weak var pdfVw: PDFView!

And use following code.

 let url = URL(fileURLWithPath: "Pass your Pdf Path here")
            if let pdfDocument = PDFDocument(url: url) {
                pdfVw.autoScales = true
                pdfVw.displayMode = .singlePageContinuous
                pdfVw.displayDirection = .vertical
                pdfVw.document = pdfDocument
Ram
  • 858
  • 1
  • 14
  • 19