How do I get the NSURLResponse before the downloadTaskWithURL finishes?

戏子无情 提交于 2019-11-27 22:42:53

问题


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 documentsDirectoryURL =  NSFileManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first as! NSURL

NSURLSession.sharedSession().downloadTaskWithURL(url, completionHandler: {
    (location, response, error) -> Void in

    if let error = error {
        println(error.description)
    }
    else {
        println("Finished downloading \"\(response.suggestedFilename)\".")
        println(location.path!)
        println("Started saving \"\(response.suggestedFilename)\".")
        if NSFileManager().moveItemAtURL(location, toURL: documentsDirectoryURL.URLByAppendingPathComponent(response.suggestedFilename!), error: nil) {
            println("File saved")
        } else {
            println("The File \(response.suggestedFilename!) was not saved.")
        }

    }
}).resume()

As it is right now, response it is only accessible inside the completion handler.

My question is how to access the response before the download finishes?

I need the NSURLResponse to know:

  • expectedContentLength
  • suggestedFilename
  • MIMEType

回答1:


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)

    }
}


来源:https://stackoverflow.com/questions/30047706/how-do-i-get-the-nsurlresponse-before-the-downloadtaskwithurl-finishes

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