IOS development realizes the basic function of the downloader (1) _ios

Source: Internet
Author: User

Today, we do a demo of the Downloader, which is to download the specified file from the locally configured Apache server. This time, we download the Html.mp4 file under the server root directory.
By convention, we first create a URL object and a request.
  Nsurl *url = [Nsurl urlwithstring:@ " http://127.0.0.1/html.mp4 "];
Nsurlrequest *request = [Nsurlrequest Requestwithurl:url];
Here are two points to note, first, the string of this URL is all in English, if there is Chinese in the string, we can not call URLWithString: This method, but to first put the URL string into a string object, The string is then passed through the  
[urlstring stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]
method, or you cannot request it normally. &NBSP
because it is a download operation, we need to use the Nsurlconnection proxy method, provided that the proxy for the Connection object and object is created first. &NBSP
//Establish a connection, immediately execute
[nsurlconnection connectionwithrequest:request delegate:self]; 
  Now the problem comes, agent more than one optional,<nsurlconnectiondownloaddelegate> and <nsurlconnectiondatadelegate>, first Contact, Instinctively chose the first agent (because from the name of the first most like). If you think like me, that's wrong, the first agent in the implementation of the method, you can actually get the data, but do not know where the data exists, not the path we specify, you can try.
  Good, after the first failure, we select the second agent, into the header file, we saw four methods:

Get response
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response;
Get Data
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *);
Disconnect
-(void) connectiondidfinishloading: (nsurlconnection *) connection;
Error occurred
-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error; 

We can clearly understand the role of each method, and you are interested in printing the parameters of each method. Take a look.
What we need to add here is that we've added a couple of attributes

File Download Stream
@property (strong, nonatomic) Nsoutputstream *filestream;
The total length of
the record file @property (assign, nonatomic) long long filelength;
The current length
of the file @property (assign, nonatomic) long long currentfilelength; 

As for Nsoutputstream, there is also a nsfilehandle that can be compared to him, but the latter will cause the file to be repeatedly appended. So we choose the former. According to the class name we can infer that there should be another nsinputstream, yes, a download stream, an upload stream.

first step. in the method of getting the response, we get the total length of the file from the response parameter, and the file length of the currently downloaded files is 0, which opens a download stream saved to the specified path, where we save to the desktop.

Get response
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (nsurlresponse *) Response
{
  self.filelength = response.expectedcontentlength;
  The current file length is 0
  self.currentfilelength = 0;
  Self.filestream = [[Nsoutputstream alloc] inittofileatpath:@ "/users/xxx/desktop/html.mp4" append:yes];
  [Self.filestream open];
}

Step two. we get the data, and if you print the data in this method, you'll see that when the file is large enough (a few m on the line), the method is called multiple times, that is to say, get the data multiple times. So we are stitching the data in this method, but also to avoid the data splicing caused by excessive memory. We accumulate the length of the downloaded data, calculate the percentage of the download, and write to the data stream. When calculating percentages, remember the conversion type Oh, otherwise the result is 0, except the last one is 1.

Get Data
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data
{
//  NSLog (@ "Did receive:%@", data);
  Self.currentfilelength + = Data.length;
  float progresspercent = (float) self.currentfilelength/self.filelength;
  NSLog (@ "have downloaded:%f", progresspercent);
  [Self.filestream write:data.bytes maxLength:data.length];
}

One last step. In fact, there are two methods, one is the download complete call, the other is the download failure call. It is important to note that the file output stream needs to be closed regardless of whether the download succeeds or fails.

Disconnect
-(void) connectiondidfinishloading: (nsurlconnection *) connection
{
  NSLog (@ "connection ended");
  [Self.filestream close];
}

Error occurred
-(void) connection: (Nsurlconnection *) connection didfailwitherror: (nserror *) error
{
  NSLog (@ "%@", error);
  [Self.filestream close];
} 

This is just the basic implementation of the download function, next will add the download progress bar, and the download operation with multiple optimization (multithreading, breakpoint, etc.), and finally the download operation will be encapsulated.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

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.