PDFDocument not loading file from URL

孤街浪徒 提交于 2021-01-29 09:01:09

问题


I am using PDFKit to show a PDF file within a PDFView with the pdfView.document = document function.

Here's the problem, I am also using the UIDocumentPicker API and whenever I retrieve a document url from the didPickDocumentAt url delegate method, the url string comes in the following form:

file:///private/var/mobile/Containers/Data/Application/09281711-BFB5-4B74-94A1-473F9B460EBD/tmp/com.ivancantarino.Cozynote-Inbox/Documento%20PDF.pdf

If I later try to preview that document with PDFKit it doesn't instantiate the document itself.

Here's a sample code:

let pdfView = PDFView()
pdfView.autoScales = true
view.addSubview(pdfView)
pdfView.frame = view.frame

// ... getting the document url, which comes in the following form: 
// file:///private/var/mobile/Containers/Data/Application/09281711-BFB5-4B74-94A1-  473F9B460EBD/tmp/com.ivancantarino.Cozynote-Inbox/Documento%20PDF.pdf
// I'm saving the URL as a string, due to the databse entry
let url: String = ...
let document = PDFDocument(url: url)
pdfView.document = document

The documentvariable is always nil, it doesn't recognize the url as a legit path.

Am I doing something wrong here, or there's a way to do this in any different way?

thanks.


回答1:


Delegate:- UIDocumentInteractionControllerDelegate

   func downloadPdf(){
        // Create destination URL

        let documentsUrl:URL =  (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last as URL?)!
        let destinationFileUrl = documentsUrl.appendingPathComponent(fileName+".pdf")

        //Create URL to the source file you want to download

        let strUrl = "Your api URL"
        let pdf = strUrl
        let fileURL = URL(string: strUrl)
        print("file url -> \(String(describing: fileURL))")

        let isFileFound:Bool? = FileManager.default.fileExists(atPath: destinationFileUrl.path)
        if isFileFound == true
        {
            if pdf != ""  {
                UIApplication.shared.openURL(URL(string: pdf)!)
            }
        }
        else{
            SVProgressHUD.show(withStatus: "Downloading...")
            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 {
                        SVProgressHUD.dismiss()
                        print("Successfully downloaded. Status code: \(statusCode)")

                    }
                      do{
                        if(FileManager.default.fileExists(atPath: destinationFileUrl.path))
                        {
                            try FileManager.default.removeItem(at: destinationFileUrl)
                            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)

                            self.showFileWithPath(path: destinationFileUrl.path)
                        }
                        else
                        {
                            try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                            self.showFileWithPath(path: destinationFileUrl.path)
                            SVProgressHUD.dismiss()
                        }
                    }
                    catch (let writeError)
                    {
                        print("Error creating a file \(destinationFileUrl) : \(writeError)")
                    }

                } else {
                    SVProgressHUD.dismiss()
                    print("Error took place while downloading a file. Error description: %@", error?.localizedDescription ?? "Errorr.....");
                }
            }
            task.resume()
        }
    }

func showFileWithPath(path: String){
        DispatchQueue.main.async {
            SVProgressHUD.dismiss()
            let isFileFound:Bool? = FileManager.default.fileExists(atPath: path)
            if isFileFound == true
            {
                let viewer = UIDocumentInteractionController(url: URL(fileURLWithPath: path))
                viewer.delegate = self
                //viewer.presentOpenInMenu(from: self.view.frame, in: self.view, animated: true)
                viewer.presentPreview(animated: true)
            }
        }
    }

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


来源:https://stackoverflow.com/questions/59570729/pdfdocument-not-loading-file-from-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!