Swift網路開發-在DownloadTask完成前擷取Resposne

來源:互聯網
上載者:User

標籤:swift   response   download   下載   

原創Blog,轉載請註明出處
blog.csdn.net/hello_hwc

前言:這是今天在StackOverflow上給阿三回答的一個問題,在這裡寫成部落格,方便遇到同樣問題的人

原理:

  1. 用DataTask擷取Response,並且將DataTask轉變成DownloadTask - 對應代理函數didReceiveResponse
  2. 在轉變成downloadTask後,開始downloadTask-對應代理函數didBecomeDownloadTask
  3. 在download完成後,儲存檔案-對應代理函數didFinishDownloadingToURL

注意:

  • Demo沒有進行錯誤處理
  • Demo沒有寫斷點續傳的部分

這些在我之前網路開發的部分講的很清楚,不懂的可以找一下我之前的部落格
或者到我的iOS SDK詳解專欄裡找一下

http://blog.csdn.net/column/manage.html?alias=huangwenchen-ios-sdk

完整代碼
建立一個single view的swift工程,拷貝如下代碼,就能看到效果了。

import UIKitclass 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()    }    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)    }}

Swift網路開發-在DownloadTask完成前擷取Resposne

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.