How do I get the NSURLResponse before the downloadTaskWithURL finishes?

扶醉桌前 提交于 2019-11-29 05:17:46

Do not use Shared session

Keep a session property,use this function to init.

 init(configuration configuration: NSURLSessionConfiguration?,
      delegate delegate: NSURLSessionDelegate?,
 delegateQueue queue: NSOperationQueue?) -> NSURLSession

Then use dataTask to download image

In this delegate method you can get Response

Then change the dataTask to downlaodTask

optional func URLSession(_ session: NSURLSession,
            dataTask dataTask: NSURLSessionDataTask,
  didReceiveResponse response: NSURLResponse,
   completionHandler completionHandler: (NSURLSessionResponseDisposition) -> Void)

Example code:

 import UIKit
class ViewController: UIViewController,NSURLSessionDelegate,NSURLSessionDataDelegate,NSURLSessionDownloadDelegate{
    var session:NSURLSession?
    var dataTask:NSURLSessionDataTask?
    let url = NSURL(string:"http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg")!
    var infoDic = NSMutableDictionary()
    override func viewDidLoad() {
        super.viewDidLoad()
        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        let manqueue = NSOperationQueue.mainQueue()
        session = NSURLSession(configuration: configuration, delegate:self, delegateQueue: manqueue)
        dataTask = session?.dataTaskWithRequest(NSURLRequest(URL: url))
        dataTask?.resume()

        // Do any additional setup after loading the view, typically from a nib.
    }
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveResponse response: NSURLResponse, completionHandler: (NSURLSessionResponseDisposition) -> Void) {
        NSLog("%@",response.description)
        completionHandler(NSURLSessionResponseDisposition.BecomeDownload)
    }
    func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask) {
        downloadTask.resume()
    }
    func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didFinishDownloadingToURL location: NSURL) {
        NSLog("%@",location);
        //Get response
        NSLog("%@", downloadTask.response!.description)

    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!