2

我已经实现了一个自定义 PDFView,它可以从云端和本地加载 pdf 文件(如果有)。对于本地实例,一切都按预期快速加载,但是当 url 不是本地的,即来自服务器时可能需要一段时间,我想在 PDFView 加载文件时添加一个 UIActivityIndi​​cator,有没有办法让我们知道像要收听以跟踪此情况的代表或通知?

我的实现基本上如下:

let url = ReportsRepository.shared.getReportUrl(id: "1234")

self.pdfView.document = PDFDocument(url: url)

在此之后,如果 URL 来自服务器应用程序似乎冻结,所以我需要在这里添加一个 UIActivityIndi​​cator,问题是如何使用 PDFKit 停止它?

4

2 回答 2

3

我已经完成了使用后台队列。这是我的代码。

//Some loading view here
    DispatchQueue.global(qos: .background).async {

        if let url = URL(string: self.selectedWebUrl) {
            if let pdfDocument = PDFDocument(url: url) {
                DispatchQueue.main.async {
                   //Load document and remove loading view
                    self.pdfView.displayMode = .singlePageContinuous
                    self.pdfView.autoScales = true
                    self.pdfView.displayDirection = .vertical
                    self.pdfView.document = pdfDocument

                }
            } else {
                DispatchQueue.main.async {
                    //not able to load document from pdf
                    //Remove loading view

                }
            }
        } else {
            DispatchQueue.main.async {
                //Wrong Url show alert or something
                //Remove loading view

            }
        }
    }
于 2020-03-30T11:09:48.650 回答
1

另一种加载方法PDFDocument是传入原始数据。

如果这是我的问题,我会通过这样的方法异步加载数据:

func loadAndDisplayPDF() {

    // file on the local file system
    let requestURL = URL(fileURLWithPath: "/tmp/MyResume.pdf")! 

    // remote pdf
    //let requestURL = URL(string: "http://www-personal.umich.edu/~myke/MichaelDautermannResume.pdf")!
    let urlRequest = URLRequest(url: requestURL)
    let session = URLSession.shared

    if requestURL.isFileURL == false {
        print("this is a good place to bring up a UIActivityIndicator")
    }
    let task = session.dataTask(with: urlRequest) {
        (data, response, error) -> Void in

        if let actualError = error
        {
            print("loading from \(requestURL.absoluteString) - some kind of error \(actualError.localizedDescription)")
        }

        if let httpResponse = response as? HTTPURLResponse
        {
            let statusCode = httpResponse.statusCode

            if (statusCode == 200) {
                print("file downloaded successfully.")
            } else  {
                print("Failed")
            }
        }

        if let actualData = data {
            print("data length is \(actualData.count)")
            self.pdfView = PDFView(frame: CGRect(x: 10, y: 10, width: 200, height: 200))
            if let actualPDFView = self.pdfView {
                actualPDFView.document = PDFDocument(data: actualData)
                self.view = actualPDFView
            }
        }
        print("all done")
    }
    task.resume()
}

您可以立即显示 UIActivityIndi​​cator(当您检测到它是远程的时),或者您可以设置一个计时器以在 1/2 - 1 秒后触发,在 PDF 文件即将显示时使两者无效和/删除。

于 2018-05-25T13:24:39.580 回答