iOS Development Network Programming--use Nsurlconnection to implement large file breakpoint continuation download + use output stream instead of file handle

Source: Internet
Author: User

In this article, in the previous iOS development of the network programming-using Nsurlconnection to achieve large file breakpoint continuation download, the use of output stream instead of file handle to achieve large file breakpoint continuation.

In the actual development, the input and output flow with less, but it is very convenient to use. The input and output streams used in iOS development are almost the same as the input and output streams in Java, and they are essentially a meaning: the data returned by the network is treated as a stream.

Input and output understanding: Where to enter? Where is the output? This question is not difficult to understand, the input and output is to stand the server perspective to think, the following diagram to explain:

Code keywords:

1. Create the output stream in the proxy method that receives the response header (according to the diagram above, the download naturally needs to create the output stream Nsoutputstream).

2, write the data in the proxy method of receiving the data, note that it is written with a data byte (data.bytes).

3. Finally, close the output stream in the downloaded proxy method.

   

API interface for doing code exercises:

MP4 Little Video: Http://120.25.226.186:32812/resources/videos/minion_01.mp4

The Complete key code:

1 #import "ViewController.h"2 3 @interfaceViewcontroller ()4 @property (nonatomic, assign) Nsinteger Totalszie;5 @property (nonatomic, assign) Nsinteger Currentszie;6@property (nonatomic, strong) NSString *FileName;7 /** Path of the file*/8@property (nonatomic, strong) NSString *FullPath;9 /** Request Object*/Ten@property (nonatomic, strong) Nsurlconnection *Connect; One /** Output Stream*/ A@property (nonatomic, strong) Nsoutputstream *stream; -@property (Weak, nonatomic) Iboutlet Uiprogressview *Progressview; - @end the  - @implementationViewcontroller - #pragmaMark---------------------- - #pragmaMark Events +-(Ibaction) Downloadbtnclick: (ID) Sender - { +      A //[[Nsfilemanager Defaultmanager] RemoveItemAtPath:self.fullPath Error:nil]; at      - [SELF DOWNLOAD]; - } --(Ibaction) Cancelbtnclick: (ID) Sender - { -     //canceling a network request in [Self.connect Cancel]; - } to  + #pragmaMark---------------------- - #pragmaMark Methods the-(void) Download * { $NSLog (@"------");Panax Notoginseng     //1. Determine the URL -Nsurl *url =[nsurl urlwithstring:@"Http://120.25.226.186:32812/resources/videos/minion_01.mp4"]; the      +     //2. Create a Request object ANsmutableurlrequest *request =[Nsmutableurlrequest Requestwithurl:url]; the      +     //set the request header information to indicate that only a subset of the data is requested for the resource -     /* $ bytes=0-1000 means downloading 0~1000 data $ bytes=0-means download starts from 0 until download is complete - bytes=100-means download starts from 0 until download is complete -      */ theNSString *range = [NSString stringWithFormat:@"bytes=%zd-", Self.currentszie]; -[Request Setvalue:range Forhttpheaderfield:@"Range"];WuyiNSLog (@"%@", range); the      -     //3. Sending an asynchronous request WuSelf.connect = [Nsurlconnection connectionwithrequest:requestDelegate: self]; - } About  $ #pragmaMark---------------------- - #pragmaMark Nsurlconnectiondatadelegate --(void) Connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response - { ANSLog (@"--didreceiveresponse-"); +      the     //determine if you have downloaded the -     if(Self.currentszie >0) { $         return; the     } the      the     //0. Get the total size of the file the     //Expectedcontentlength is the size of the data requested, not the entire -Self.totalszie =response.expectedcontentlength; in      the     //1. Get the name of the file theSelf.filename =Response.suggestedfilename; About      the     //2. Get the full path of the file the     //caches theNSString *caches =[Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject]; +      -NSString *fullpath =[Caches stringByAppendingPathComponent:self.fileName]; theSelf.fullpath =FullPath;Bayi      the     //3. Create an output stream the     /* - first parameter: The address where the data is written - Second parameter: Indicates if you want to append a breakpoint to the continuation of the the      */ theNsoutputstream *stream =[[Nsoutputstream Alloc]inittofileatpath:fullpath append:yes]; theSelf.stream =stream; the      -     //4. Open the data stream the     //If the file does not exist, an empty file is created automatically the [Self.stream Open]; the }94  the-(void) Connection: (Nsurlconnection *) connection didreceivedata: (NSData *) Data the { the     //Write Data98     /* About first parameter: The data to be written - second parameter: Length of data101      */102 [Self.stream write:data.bytes maxLength:data.length];103     104      the     //3. Accumulate the currently downloaded data size106Self.currentszie + =data.length;107     108     //4. Calculate the download progress of the file109NSLog (@"%f",1.0* Self.currentszie/Self.totalszie); the     111Self.progressView.progress =1.0* Self.currentszie/Self.totalszie; the }113  the-(void) Connectiondidfinishloading: (Nsurlconnection *) Connection the { theNSLog (@"%@", Self.fullpath);117     118     //1. Turn off the output stream119 [Self.stream close]; -     121     //2. Clear the pointer122Self.stream =Nil;123 }124  the-(void) Connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) Error126 {127 } - 129 @end

iOS Development Network Programming--use Nsurlconnection to implement large file breakpoint continuation download + use output stream instead of file handle

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.