iOS development--Network Swift chapter &nsurlsession loading data, downloading, uploading files

Source: Internet
Author: User

Nsurlsession loading data, downloading, uploading files
The Nsurlsession class supports three types of tasks: loading data, downloading, and uploading. The following examples are presented below.1, loading data using the database taskCreated using the global Sharedsession () and Datataskwithrequest methods.
1 func sessionloaddata () {2     //Create a Nsurl object3Let urlstring:string="http://hangge.com"4var url:nsurl! = Nsurl (string: urlstring)5     //Create Request Object6var request:nsurlrequest =nsurlrequest (Url:url)7      8Let session =nsurlsession.sharedsession ()9    Tenvar datatask =session.datataskwithrequest (Request, OneCompletionhandler: {(data:nsdata!, response:nsurlresponse!, error:nserror!), Voidinch A             ifError! =nil{ -println (error?). Code) -println (error?). Description) the}Else{ -var str = nsstring (data:data!, encoding:nsutf8stringencoding) - println (str) -             } +}) asNsurlsessiontask -       +     //To start a task by using the Resume method A Datatask.resume () at}


2. Use download task to download the file(1) No need to get progressUse the Sharedsession () and Downloadtaskwithrequest methods to
1 func sessionsimpledownload () {2     //3var url = nsurl (string:"Http://hangge.com/blog/images/logo.png")4     //Request5var request:nsurlrequest = nsurlrequest (url:url!)6      7Let session =nsurlsession.sharedsession ()8      9     //Download TaskTenvar downloadtask =session.downloadtaskwithrequest (Request, OneCompletionhandler: {(location:nsurl!, response:nsurlresponse!, error:nserror!), Voidinch A             //Output download File The original storage directory -println"location:\ (location)") -             //Location Conversion thevar Locationpath =Location.path -             //Copy to User directory -Let documnets:string = nshomedirectory () +"/documents/1.png" -             //creating a File Manager +var Filemanager:nsfilemanager =Nsfilemanager.defaultmanager () -Filemanager.moveitematpath (locationpath!, Topath:documnets, Error:nil) +println"new Location:\ (documnets)") A     }) at       -     //To start a task by using the Resume method - Downloadtask.resume () -}


(2) real-time access to progress
You need to use a custom Nsurlsession object and a Downloadtaskwithrequest method
1 Import UIKit2  3 classViewcontroller:uiviewcontroller, nsurlsessiondownloaddelegate {4  5     Overridefunc viewdidload () {6 super.viewdidload ()7          8 sessionseniordownload ()9     }Ten       One     //Download File A func sessionseniordownload () { -         // -var url = nsurl (string:"Http://hangge.com/blog/images/logo.png") the         //Request -var request:nsurlrequest = nsurlrequest (url:url!) -           -Let session = Currentsession () asnsurlsession +           -         //Download Task +var downloadtask =session.downloadtaskwithrequest (Request) A           at         //To start a task by using the Resume method - Downloadtask.resume () -     } -       -     //Create a download mode -Func currentsession ()nsurlsession{ invar predicate:dispatch_once_t =0 -var currentsession:nsurlsession? =Nil to          +Dispatch_once (&predicate, { -var config =nsurlsessionconfiguration.defaultsessionconfiguration () theCurrentsession = Nsurlsession (Configuration:config,Delegate: Self, Delegatequeue:nil) *         }) $         returncurrentsession!Panax Notoginseng     } -       the     //Download Agent method, download end + func urlsession (session:nsurlsession, Downloadtask:nsurlsessiondownloadtask, A Didfinishdownloadingtourl Location:nsurl) { the         //End of Download +println"End of Download") -           $         //Output download File The original storage directory $println"location:\ (location)") -         //Location Conversion -var Locationpath =Location.path the         //Copy to User directory -Let documnets:string = nshomedirectory () +"/documents/1.png"Wuyi         //creating a File Manager thevar Filemanager:nsfilemanager =Nsfilemanager.defaultmanager () -Filemanager.moveitematpath (locationpath!, Topath:documnets, Error:nil) Wuprintln"new Location:\ (documnets)") -     } About       $     //Download Agent method, listen to download progress - func urlsession (session:nsurlsession, Downloadtask:nsurlsessiondownloadtask, - Didwritedata Byteswritten:int64, Totalbyteswritten:int64, Totalbytesexpectedtowrite:int64) { -         //Get Progress Avar written:cgfloat =(CGFloat) (Totalbyteswritten) +var total:cgfloat =(CGFloat) (totalbytesexpectedtowrite) thevar pro:cgfloat = written/ Total -println"Download progress: \ (PRO)") $     } the       the     //Download Agent method, download offset the func urlsession (session:nsurlsession, Downloadtask:nsurlsessiondownloadtask, the didresumeatoffset Fileoffset:int64, Expectedtotalbytes:int64) { -         //download offset, mainly used to pause the resume in     } the   the     Overridefunc didreceivememorywarning () { About super.didreceivememorywarning () the     } the}


3. Use upload task to upload files
1 func sessionupload () {2     //Upload Address3var url = nsurl (string:"http://hangge.com/")4     //Request5var request:nsurlrequest = nsurlrequest (url:url!)6      7Let session =nsurlsession.sharedsession ()8      9     //Uploading data streamsTenLet documents = nshomedirectory () +"/documents/1.png" Onevar imgdata =NSData (contentsoffile:documents) A       -var uploadtask =session.uploadtaskwithrequest (Request, Fromdata:imgdata) { -(data:nsdata!, response:nsurlresponse!, error:nserror!) -Voidinch the         //Once the upload is complete -println"Upload Complete") -     } -       +     //To start a task by using the Resume method - Uploadtask.resume () +}

iOS development--Network Swift chapter &nsurlsession loading data, downloading, uploading files

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.