How do I get the NSURLResponse before the downloadTaskWithURL finishes?

后端 未结 1 476
一向
一向 2020-12-17 06:54

This is my code for download :

let url = NSURL(string:\"http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg\")!

let doc         


        
相关标签:
1条回答
  • 2020-12-17 07:18

    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)
    
        }
    }
    
    0 讨论(0)
提交回复
热议问题