iOS development--the function of the downloader is basically realized

Source: Internet
Author: User

Today, I did a demo of a downloader that downloads the specified file from the locally configured Apache server. This time, we download the Html.mp4 file under the root directory of the server.

By convention, we first create a URL object and a request.

Nsurl *url = [Nsurl urlwithstring:@ "http://127.0.0.1/html.mp4"*request = [ Nsurlrequest Requestwithurl:url];

Here are two points to note, first, the URL of the string is all in English, if the string appears in Chinese, we can not directly call URLWithString: This method, but to first put the URL string into a String object, and then the string through the

[URLString stringbyaddingpercentescapesusingencoding:nsutf8stringencoding]

method is not available, otherwise it cannot be requested properly.

Because it is a download operation, we need to use the proxy method of nsurlconnection, if we create a proxy for the Connection object and object first.

// Establish a connection, execute immediately delegate: self];

Now that the problem has come, the agent has more than one optional,<nsurlconnectiondownloaddelegate> and <nsurlconnectiondatadelegate> First Contact, Instinctively chose the first agent (since the first one is most like the name). 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 it.

OK, after the first failure, we select the second agent, enter the header file, we see four methods:

 //  get response -( void ) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *  //  get Data -(void ) Connection: ( Nsurlconnection *) connection didreceivedata: (nsdata *) data;  //  disconnect -(void ) Connectiondidfinishloading: (nsurlconnection * // -(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 to see.

What we need to add here is that we've added a couple of attributes

///   File Download stream @property (strong, Nonatomic) Nsoutputstream *FileStream; ///   record file total length long   filelength; ///   file Current length long currentfilelength; 

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

The first step. In the method of obtaining the response, we get the total length of the file from the response parameter, and set the current downloaded file length is 0, open a save to the specified path of the download stream, here we save to the desktop.

 //  get response -( void ) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse * ) response{self.filelength  = //  current file length 0     Self.currentfilelength = 0   = [[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 way, you'll find that when the file is big enough (a few m on the line), the method is called multiple times, that is, the data is fetched multiple times. So we are splicing the data in this method, but also to avoid the data stitching to take up too much memory. We accumulate the length of the downloaded data, calculate the percentage that has been downloaded, and write to the data stream. When calculating the percentage, 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 (@ "havedownloaded:%f", progresspercent);    [Self.filestream write:data.bytes maxLength:data.length];}

A final step. is actually two methods, one is the download completes the call, and the other is the download failure call. It is important to note that the file output stream needs to be closed regardless of the success or failure of the download.

// Disconnect -(void) connectiondidfinishloading: (nsurlconnection *) connection{    NSLog (@ " end of connection ");    [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, the next step is to add the download progress bar, and the download operation is more optimized (multi-threaded, breakpoint continuation, etc.), and finally the download operation is encapsulated.

Thanks for reading!

iOS Development-the basic implementation of the Downloader's functionality

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.