Original blog, reproduced please indicate the source
Blog.csdn.net/hello_hwc
This is a question for three O to answer on StackOverflow today, write a blog here, convenient for people who meet the same problem
Principle:
- Get response with Datatask, and convert Datatask to downloadtask-corresponding agent function
didReceiveResponse
- After turning into Downloadtask, the downloadtask-corresponding agent function is started
didBecomeDownloadTask
- After the download is complete, save the file-corresponding agent function
didFinishDownloadingToURL
Attention:
- Demo does not handle error
- Demo does not write the section of the breakpoint to continue the transmission
These before me in the Network Development section to speak very clearly, does not understand can look for my previous blog
Or check out my iOS SDK for a detailed column.
Http://blog.csdn.net/column/manage.html?alias=huangwenchen-ios-sdk
Full code
Create a single view of the Swift project, copy the following code, you can see the effect.
ImportUikitclass Viewcontroller:uiviewcontroller,nsurlsessiondelegate,nsurlsessiondatadelegate, nsurlsessiondownloaddelegate{varSession:nsurlsession? varDatatask:nsurlsessiondatatask? LetUrl=Nsurl (string:"Http://www.zastavki.com/pictures/originals/2013/Photoshop_Image_of_the_horse_053857_.jpg")! varInfodic=Nsmutabledictionary () override Func Viewdidload () {Super.Viewdidload () LetConfiguration=Nsurlsessionconfiguration.Defaultsessionconfiguration () LetManqueue=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:nsurl Response, Completionhandler: (nsurlsessionresponsedisposition) -Void) {NSLog ("%@", response.Description) Completionhandler (nsurlsessionresponsedisposition.becomedownload)} func urlsession (Session:nsurlsession, Datatask:nsurlsessiondatatask, Didbecomedownloadtask downl Oadtask:nsurlsessiondownloadtask) {Downloadtask.Resume ()} func urlsession (Session:nsurlsession, Downloadtask:nsurlsessiondownloadtask, Didfinishdownloadingtourl Location:nsurl) {NSLog ("%@", location);//get ResponseNSLog ("%@", Downloadtask.Response!.Description)}}
Swift Network Development-get Resposne before Downloadtask is complete