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