我已经实现了一个自定义PDFView,它可以从云和本地加载pdf文件(如果有的话)。对于本地实例,所有内容都加载得很快,但是当url不是本地时,即从服务器上可能需要一段时间,我想在PDFView加载文件时添加UIActivityIndicator,有没有办法让我们知道如何代表或通知听取跟踪这个?
我的实现基本如下:
let url = ReportsRepository.shared.getReportUrl(id: "1234")
self.pdfView.document = PDFDocument(url: url)
在此之后,如果URL来自服务器,应用程序似乎冻结了,所以我需要在这里添加一个UIActivityIndicator,问题是如何使用PDFKit来阻止它?
加载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()
}
你可以立即显示UIActivityIndicator(当你检测到它是遥控器时),或者你可以设置一个计时器在1/2 - 1秒后启动,当PDF文件即将显示时,无效和/或删除两者。