Network Programming in iOS

Source: Internet
Author: User

In the era of mobile internet, almost all applications need to use the network download, than tablet loading, music download, installation package download, and so on, let's see how to download

I. Download of the file we use get to request data and parse the requested binary data into the file, first we first introduce a third-party progress bar, and initialize

-(void) viewdidload {    [super Viewdidload];         // Set Background color    self.view.backgroundcolor=[Uicolor greencolor];         // introducing a third-party progress bar    Self.da=[[dacircularprogressview Alloc] Initwithframe:cgrectmake (375/2.0-  -  -  - )];    [Self.view AddSubview:self.da]; }

Second, set up the file, start to download data

#pragmaMark-Start downloading data-(void) start{//Set network resource addressNSString * str=@"http://dl.g.youku.com/20151023/1445588041_20151023XXXX.apk"; Nsurl* Url=[Nsurl Urlwithstring:str]; Nsmutableurlrequest* request=[Nsmutableurlrequest Requestwithurl:url]; //set Range, which represents the starting position of the request, and the default location at the beginning is 0[Request Setvalue:[nsstring stringWithFormat:@"bytes=%ld-", Self.currentlength] Forhttpheaderfield:@"Range"]; //Send Requestself.conn= [Nsurlconnection connectionwithrequest:requestDelegate: self];}

Third, the implementation of proxy methods

We usually use the variable Nsmutabledata to save the downloaded data when downloading, but in this way will cause the memory to be bigger, originally the memory of the cell phone is limited, so we need to optimize it, prevent the flash back, the solution is we do not adopt the request data cache with memory, Instead, take the time to download the cache in a timely manner, each download is written to the file, the code is as follows

@interfaceViewcontroller () <NSURLConnectionDataDelegate>/** Current Download length*/@property (nonatomic,assign) Nsinteger currentlength;/** Total file length*/@property (nonatomic,assign) Nsinteger totallength;/** Link Length*/@property (nonatomic,strong) nsurlconnection*Conn;/** File Write handle*/@property (nonatomic,strong) Nsfilehandle*handle;/** Third party progress bar*/@property (nonatomic,strong) Dacircularprogressview*da;/** Third party progress bar*/@property (nonatomic,weak) Dpmeterview*DP;@end#pragmaMark-Response Proxy method, create file and file handle in sandbox-(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{if(self.totallength<=0) {Self.totallength=response.expectedcontentlength; }    //Create a file action handle    if(self.handle==Nil) {         //Get file pathNSString *path=[Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES) firstobject]; Path=[path stringbyappendingpathcomponent:@"jereh.apk"]; //Create a management classNsfilemanager * manager=[Nsfilemanager Defaultmanager];                [Manager Createfileatpath:path Contents:nil Attributes:nil]; //Initializing Management handlesself.handle=[Nsfilehandle Filehandleforwritingatpath:path]; }    }#pragmaMark-Accepts the data proxy method, writes the received data to the file, and calculates the download progress-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{//record current length, calculate percentself.currentlength+=data.length; CGFloat percent=self.currentlength*1.0/self.totallength; //move to end of file[Self.handle Seektoendoffile]; //writes the current data to a file[Self.handle Writedata:data]; //Modify the progress barself.da.progress=percent;}

Four, in the file download time we need to pause the function, how to let a download in the request to pause it? We just need to call the Cancel method to

#pragma mark-Set Pause Method-(void) pause{    [self.conn cancel];    Self.conn=nil;}

V. Closing the handle last

#pragma mark-Close handle-(void) dealloc{    [Self.handle closefile];}

Jerry Education
Source:http://www.cnblogs.com/jerehedu/
Copyright Notice: The copyright of this article belongs to cigarettes DeskJerry EducationSection Technology Co., Ltd. and blog Park are shared, welcome reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original link, otherwise reserves the right to pursue legal responsibility.
Technical Consultation:

Network Programming in iOS

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.