【问题标题】:How do I get the NSURLResponse before the downloadTaskWithURL finishes?如何在 downloadTaskWithURL 完成之前获取 NSURLResponse?
【发布时间】:2015-07-14 21:01:48
【问题描述】:

这是我的下载代码:

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:

  • 预期内容长度
  • 建议的文件名
  • MIME 类型

【问题讨论】:

标签: ios swift nsurl nsurlsession


【解决方案1】:

不要使用共享会话

保留一个会话属性,使用这个函数来初始化。

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

然后使用dataTask下载图片

在这个委托方法中你可以获得Response

然后将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)

    }
}

【讨论】:

  • 感谢您的回答,但我不想使用缓冲区,我想将其保存到 tmp 文件,缓冲区使用内存,我想将其保存到磁盘,和我一样正在按照我的代码所示进行操作,DownloadTaskwithurl 是我的问题。
  • 我更新了代码,这样你就不需要缓冲了
  • 您可以使用 dataTask 获取响应,然后将数据任务转换为 DownloadTask。所以这被保存到文件中。您可以在didFinishDownloadingToURL 中获取该文件
  • 和你的代码一样。tmp文件位于location,你可以移动到其他路径。
  • 查看更新代码,我测试了一下,效果很好。你可以得到downloadTask.response的回复,忘记我之前说的了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多