代码之家  ›  专栏  ›  技术社区  ›  kishore

无法在iOS swift中打开下载的pdf路径?

  •  -1
  • kishore  · 技术社区  · 7 年前

    我正在尝试实现pdf下载选项一旦用户点击下载选项pdf文件应该下载并打开。我尝试了以下链接,但不起作用 Saving PDF Files with Swift in iOS and display them 我尝试了以下代码。作为回应,它显示了我使用该路径所经过的路径,但我没有找到任何文件。

     @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()
        }
    
    1 回复  |  直到 6 年前
        1
  •  0
  •   Ram    6 年前

    嘿@kishore Apple最近添加了PDfKit框架,请尝试以下链接。

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

    在这里,您所需要做的就是在情节提要中使用一个UIView来显示Pdf文件。在Identity Inspector中,将类设置为PDFView。 像这样取出口。

    @IBOutlet weak var pdfVw: PDFView!
    

    并使用以下代码。

     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