如何在downloadTaskWithURL完成之前获取NSURLResponse?

时间:2015-05-05 08:22:05

标签: ios swift nsurl nsurlsession

这是我的下载代码:

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()

就像现在一样,响应它只能在完成处理程序中访问。

我的问题是如何在下载完成之前访问响应?

我需要NSURLResponse知道:

  • expectedContentLength
  • suggestedFilename
  • MIMEType

1 个答案:

答案 0 :(得分:4)

不要使用共享会话

保留会话属性,使用此函数进行初始化。

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

然后使用 dataTask 下载图片

在此委托方法中,您可以获得响应

然后将 dataTask 更改为 downlaodTask

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

示例代码:

 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)

    }
}