iOS Development--Network download

Source: Internet
Author: User

Here is the NSURLConnection proxy request download, and is the progress, the UI can be refreshed in real-time, as NSURLConnection to how to request, and there are several request methods please see Nsurlconnection request introduction, here we download a book as an example, the following is its address ( This is in the Baidu cloud inside, the link is someone else encrypted, all relatively long)

http://d.pcs.baidu.com/file/2b66fa1c93d8322d5299a1befc59b16c?fid=204559171-250528-1042286675318370&time=1453435914&rt=sh&sign=FDTAERV-DCb740ccc5511e5e8fedcff06b081203-X%2Bcz8N4IQb25c4wIKAyYl1HHW2M%3D&expires=8h&chkv=1&chkbd=0&chkpc=&dp-logid=498837374116132296&dp-callid=0&r=107651804

Code:

1. First drag a Progress View (progress bar) control into the storyboard2. Drag the Progress view property into the controller and add three additional attributes as follows:@interfaceViewcontroller () <Nsurlconnectiondelegate>/** Progress Bar Properties */@property (Weaknonatomic)IboutletUiprogressview *progressview;/** Total File Size */@property (Nonatomic,AssignNsuinteger totallength;/** file Current Size */@property (Nonatomic,AssignNsuinteger currentlength;/** File path */@property (Nonatomic,CopyNSString *path;@end3. Determine its URL, as well as the request, and set its proxy, then send the so-called Proxy request-(void) Viewdidload {[Super Viewdidload];1. Determine the URLNsurl *url = [Nsurl URLWithString:@ "Http://d.pcs.baidu.com/file/2b66fa1c93d8322d5299a1befc59b16c?fid=204559171-250528-1042286675318370&time= 1453435914&rt=sh&sign=fdtaerv-dcb740ccc5511e5e8fedcff06b081203-x%2bcz8n4iqb25c4wikayyl1hhw2m%3d& expires=8h&chkv=1&chkbd=0&chkpc=&dp-logid=498837374116132296&dp-callid=0&r=107651804 "] ;2. Create the Request objectNsurlrequest *request = [Nsurlrequest Requestwithurl:url];3. Agent Request/* First parameter: The second parameter of the Request object: Who becomes the agent the third parameter: startimmediately: Whether to start sending network requests immediately */Nsurlconnection *connection = [[Nsurlconnection Alloc]initwithrequest:request Delegate:Self startimmediately:NO]; [Connection start]; }4, in this demo, the agent has two methods is very important4.1, the first is just the beginning of the response, in the response header, I can get the file's estimated size and file name suffix, used to create the total size of the folder and record file, for the subsequent calculation4.2, the second is every time you receive server data, I can write data to a file, and calculate the proportion of how much each time1. Called when the server response is accepted: Response (response header)-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response {NSLog (@ "Accept to respond");1. There is an estimated file size in the response header ExpectedcontentlengthSelf. Totallength = Response. expectedcontentlength;Here you can print and look at the page's request header can also be compared to see if it is the sameNSLog (@ "totallength =%lld", response.expectedcontentlength);2, here in order to let performance better, I directly in the sandbox caches create a folder directly on the hard disk, rather than in memory2.1, here is the address for the caches in the sandbox path to add a file named Suggestedfilename file, Suggestedfilename is the response in the head, but also the name of the Baidu Cloud get you can also print to seeNSLog (@ "%@", response.suggestedfilename);NSString *path = [[Nssearchpathfordirectoriesindomains (Nscachesdirectory,Nsuserdomainmask,YES) Lastobject] Stringbyappendingstring:response. Suggestedfilename];2.2, get the address then we start to create an empty folder, and the path to the external paths property, used to get the location downloadNsfilemanager *manager = [Nsfilemanager Defaultmanager]; [Manager Createfileatpath:path Contents:Nil attributes:NIL];Self. Path = path; }2. Called when the server returns data (it is called multiple times)-(void) Connection: (Nsurlconnection *) connection Didreceivedata: (NSData *) Data {1. Create a handle to the action file and give the address of the last created folder.Nsfilehandle *handle = [Nsfilehandle Filehandleforwritingatpath:Self. path];Set the write mode, since the last write [handle seektoendoffile];2. Use the handle to write data to the file [handle writedata:data];3. Calculate the total number of data currently received this is how much data is written each time.Self. currentlength + = Data. length;//4, calculate download ratio self.progressView< Span class= "hljs-variable" >.progress = 1.0 * self.currentlength/self.totalLength;} //3. Called when the request fails-(void) connection: (nserror *) Error { nslog (@ "request Failed");} //4. Call-(void) when the request finishes (Success | failed) Connectiondidfinishloading: ( nsurlconnection *) connection {nslog ( @ "request End"); } 

Add

The only advantage in this demo is to save memory, because every write is written to the hard drive, not in memory, now you can open your own 沙盒 inside should have a PDF file is just downloaded, the most important method of this demo is:

//1.当接受到服务器响应的时候会调用:response(响应头)-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{} //2.当接受到服务器返回数据的时候调用(会调用多次)-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{}

End

iOS Development--Network download

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.