在 PDFView SWIFT 中打开存储在本地内存中的 PDF

Opening a PDF stored in local memory in a PDFView SWIFT

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

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

下面给出的代码将 return 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
    }

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

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

它returns,任务还在执行,所以路径中的文件不存在。

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

所以这里是 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