Swift 3.0:如何使用URLSessionDownloadDelegate

时间:2016-12-14 19:30:41

标签: ios pdf swift3 nsurlsessiondownloadtask

在我写的应用程序中,我需要从服务器下载PDF并将其显示在UIWebView中。为此,我获得了一些从端点检索PDF的代码(它不是一个URL,并且在台式计算机上打开了一个对话框,可以像在浏览器中一样进行保存)并加载它通过抓取名为PDFGrabber的类中的数据来到设备上:

func getPDF(completionHandler:@escaping (URL) -> Void)
{
    let theURL:String = "https://mywebsite.com/Endpoint"
    let fileURL:URL = URL(string: theURL)!
    var request = URLRequest(url: fileURL, cachePolicy: .useProtocolCachePolicy, timeoutInterval: 10.0)
    let session = URLSession.shared

    let task = session.dataTask(with: request, completionHandler: {data, response, error -> Void in

    var documentURL = (FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)).last
    documentURL = documentURL?.appendingPathComponent("MyDocument.pdf")

    do
    {
        try data?.write(to: documentURL!, options: .atomic)
        completionHandler(documentURL!)
        }
        catch
        {
            print(error)
        }
    })

    task.resume()
}

然后,在显示PDF的表格视图控制器中(让我们称之为PDFTableView,我可以在请求PDF时使用PDFGrabber中的documentURL(通过点击表格中的单元格):

PDFGrabber.getPDF(){fileURL -> () in
    DispatchQueue.main.async
    {
        if let resultController = self.storyboard!.instantiateViewController(withIdentifier: "PDFViewer") as? PDFViewer 
        {
            resultController.thePDFPath = stringURL
            self.present(resultController, animated: true, completion: nil)
        }
    }

最后,我有另一个带有UIWebView的View Controller,名为" WebView"和属性" thePDFPath"作为PDFViewer视图控制器中的字符串。在viewDidLoad()方法中,我可以说:

override func viewDidLoad()
{
    let pathToPDF:URL = URL(string: thePDFPath)!
    WebView.loadRequest(URLRequest(url: pathToPDF))
}

一起,这会将PDF加载到Web视图中。但是,加载时间可能有点慢,我希望能够使用进度条和字符串计算已将多少PDF加载到用户设备上。从其他问题来看,我收集的比我需要让我的PDFGrabber类扩展URLSessionDownloadDelegate,然后实现这些功能。获取下载的字节数很简单,因为我可以简单地去:

func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten writ: Int64, totalBytesExpectedToWrite exp: Int64)
{
    percentDownloaded = (Float(writ)/Float(exp)) * 100
    print("Progress: " + String(describing: percentDownloaded))
}

但我也希望能够在以百分比显示其进度后完全下载PDF后才能打开PDFView (我已经有了覆盖视图,做这个)。之前,我可以使用完成处理程序并等到PDF完成下载,然后打开它。

但是,这种方法不允许我访问下载的字节数;我会从

打开视图吗?
urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)

功能,还是我需要做的其他事情?

建议值得赞赏;谢谢!

1 个答案:

答案 0 :(得分:0)

导入WebKit

在这里,您可以在应用程序中加载pdf

 override func viewDidLoad() {
      super.viewDidLoad()
      // Do any additional setup after loading the view, typically from a nib.

      if let pdfURL = Bundle.main.url(forResource: "food-and-drink-menu-trafalgar-tavern", withExtension: "pdf", subdirectory: nil, localization: nil)  {
           do {
                let data = try Data(contentsOf: pdfURL)
                let webView = WKWebView(frame: CGRect(x:0,y:NavigationView.frame.size.height,width:view.frame.size.width, height:view.frame.size.height-NavigationView.frame.size.height))
                webView.load(data, mimeType: "application/pdf", characterEncodingName:"", baseURL: pdfURL.deletingLastPathComponent())
                view.addSubview(webView)

           }
           catch {
                // catch errors here
           }

      }
 }