【问题标题】:Opening a PDF stored in local memory in a PDFView SWIFT在 PDFView SWIFT 中打开存储在本地内存中的 PDF
【发布时间】:2020-02-26 11:14:28
【问题描述】:

我已经将一个 pdf 文件下载到我的缓存中。现在我希望在 PDFView 中打开这个 PDF 文件。 我已经在我的 ViewController 中添加了一个 PDFView,这里是相同的代码。

let pdfView = PDFView()
override func viewDidLoad() {
   super.viewDidLoad()
   view.addSubview(pdfView)
}

下面给出的代码将把 PDF 下载到的位置作为 URL 返回。

guard let pdfURL = downloader.downloadData(urlString: "https://www.tutorialspoint.com/swift/swift_tutorial.pdf", downloadType: DownloadType.cache.rawValue) else { return }

我检查了返回的 URL 并且文件存在。 现在在下面的代码中,我试图在 pdf 视图中打开它。

if let document = PDFDocument(url: pdfURL) {
   pdfView.document = document
}

下面给出的代码显示了下载数据的方法。

public func downloadData(urlString : String,downloadType : String)->URL?{

        let documentsUrl:URL =  FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
        var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
        try? FileManager.default.removeItem(at: destinationFileUrl)
        guard let url = URL(string: urlString)else{
            return nil
        }
        let urlSession = URLSession(configuration: .default)
        let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {

                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")

                }
                if downloadType == "cache" {
                    do {
                        try? FileManager.default.removeItem(at: destinationFileUrl)
                          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);
            }
        }
        downloadTask.resume()

        return destinationFileUrl
    }

但它似乎返回 nil 并且 if let 块中的代码没有执行。请帮忙!!

【问题讨论】:

  • downloader.downloadData 是异步的。您无法同步获取 url。把它放在它的delegate
  • 感谢您的建议。即使我正在异步执行此操作,我也获得了下载文件的有效 url,但为什么无法将 url 传递给 PDFDocument()?对此有什么想法吗?@dengApro
  • @dengApro 我已经更新了帖子,请查看 downloadData()

标签: swift pdfkit pdfview


【解决方案1】:

当然没有。 return destinationFileUrl,用它来初始化 PDF,得到 nil。

返回,此时任务还在执行,所以路径中的文件不存在。

因为下载是一个异步操作。

所以这里是 completionHandler 的闭包。

通常,转动这个

public func downloadData(urlString : String,downloadType : String)->URL?{

        let documentsUrl:URL =  FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
        var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
        try? FileManager.default.removeItem(at: destinationFileUrl)
        guard let url = URL(string: urlString)else{
            return nil
        }
        let urlSession = URLSession(configuration: .default)
        let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {

                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")

                }
                if downloadType == "cache" {
                    do {
                        try? FileManager.default.removeItem(at: destinationFileUrl)
                          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);
            }
        }
        downloadTask.resume()


        return destinationFileUrl
    }

进入

public func downloadData(urlString : String,downloadType : String, completionHandler: @escaping (URL) -> Void){

            let documentsUrl:URL =  FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first as URL!
            var destinationFileUrl = documentsUrl.appendingPathComponent("downloadedFile.pdf")
            try? FileManager.default.removeItem(at: destinationFileUrl)
            guard let url = URL(string: urlString)else{
                return nil
            }
            let urlSession = URLSession(configuration: .default)
            let downloadTask = urlSession.downloadTask(with: url) { (tempLocalUrl, response, error) in
                if let tempLocalUrl = tempLocalUrl, error == nil {

                    if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                        print("Successfully downloaded. Status code: \(statusCode)")

                    }
                    if downloadType == "cache" {
                        do {
                            try? FileManager.default.removeItem(at: destinationFileUrl)
                              try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                                completionHandler(destinationFileUrl)
                        } catch (let writeError) {
                            print("Error creating a file \(destinationFileUrl) : \(writeError)")
                        }
                    }
                } else {
                    print("Error took place while downloading a file. Error description: %@", error?.localizedDescription);
                }
            }
            downloadTask.resume()

        }

在completionHandler回调中,初始化PDF

【讨论】:

  • 非常感谢,我明白我现在做错了什么。 @dengApro
猜你喜欢
  • 1970-01-01
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-25
  • 2018-05-28
  • 2012-04-24
相关资源
最近更新 更多