Network Programming for iOS development-use NSURLConnection to implement resumable download of large files + use an output stream instead of a file handle, and use nsurlsession for resumable upload

Source: Internet
Author: User

Network Programming for iOS development-use NSURLConnection to implement resumable download of large files + use an output stream instead of a file handle, and use nsurlsession for resumable upload

This article explains network programming in the previous iOS development-using NSURLConnection for resumable download of large files, and using the output stream instead of the file handle for resumable upload of large files.

In actual development, the input and output streams are rarely used, but they are also very convenient to use. The input/output stream used by iOS development is almost the same as the input/output stream in Java. In essence, it also means processing the data returned by the Network as a stream.

Understanding of input and output: Where is the input? Where is the output? It is not hard to understand this problem. The input and output must be considered from the server perspective. The following figure is used to explain the problem:

Code keywords:

1. Create an output stream in the proxy method that receives the Response Header (according to the figure above, the NSOutputStream must be created for downloading ).

2. write data in the proxy method for receiving data. Note that data bytes (data. bytes) are written ).

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

   

APIs used for code exercises:

MP4 video: http: // 120.25.226.186: 32812/resources/videos/minion_01.mp4

Complete key code:

1 # import "ViewController. h "2 3 @ interface ViewController () 4 @ property (nonatomic, assign) NSInteger totalSzie; 5 @ property (nonatomic, assign) NSInteger currentSzie; 6 @ property (nonatomic, strong) NSString * fileName; 7/** file path */8 @ property (nonatomic, strong) NSString * fullPath; 9/** request object */10 @ property (nonatomic, strong) NSURLConnection * connect; 11/** output stream */12 @ property (nonatomic, strong) NSOutputStream * stream; 13 @ property (weak, nonatomic) IBOutlet UIProgressView * progressView; 14 @ end 15 16 @ implementation ViewController 17 # pragma mark -------------------- 18 # pragma mark Events 19-(IBAction) downloadBtnClick :( id) sender 20 {21 22 // [[NSFileManager defaultManager] removeItemAtPath: self. fullPath error: nil]; 23 24 [self download]; 25} 26-(IBAction) cancelBtnClick :( id) send Er 27 {28 // cancel network request 29 [self. connect cancel]; 30} 31 32 # pragma mark -------------------- 33 # pragma mark Methods 34-(void) download 35 {36 NSLog (@ "------"); 37 // 1. confirm url 38 NSURL * url = [NSURL URLWithString: @ "http: // 120.25.226.186: 32812/resources/videos/minion_01.mp4"]; 39 40 // 2. create a request object 41 NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; 42 43 // set request header information, indicating that only part of the data of this resource needs to be requested 44/* 45 bytes = 0-1000 indicates the download is 0 ~ 1000 data 46 bytes = 0-indicates that the download starts from 0 until the download is completed 47 bytes = 100-indicates that the download starts from 0 until the download is completed 48 */49 NSString * range = [NSString stringWithFormat: @ "bytes = % zd-", self. currentSzie]; 50 [request setValue: range forHTTPHeaderField: @ "Range"]; 51 NSLog (@ "% @", range); 52 53 // 3. send asynchronous request 54 self. connect = [NSURLConnection connectionWithRequest: request delegate: self]; 55} 56 57 # pragma mark -------------------- 58 # pragma mark NSURLConnectionDataDelegate 59-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response 60 {61 NSLog (@ "-- didReceiveResponse-"); 62 63 // determine whether 64 if (self. currentSzie> 0) {65 return; 66} 67 68 // 0. obtain the total file size 69 // expectedContentLength is the data size of this request, not the whole 70 self. totalSzie = response. expectedContentLength; 71 72 // 1. get the file name 73 self. fileName = response. suggestedFilename; 74 75 // 2. obtain the full path of the file 76 // caches 77 NSString * caches = [Export (NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 78 79 NSString * fullPath = [caches stringByAppendingPathComponent: self. fileName]; 80 self. fullPath = fullPath; 81 82 // 3. create output stream 83/* 84 first parameter: write data address 85 second parameter: indicates whether to append resumable upload. You must append 86 */87 NSOutputStream * stream = [[NSOutputStream alloc] initToFileAtPath: fullPath append: YES]; 88 self. stream = stream; 89 90 // 4. open the data stream 91 // if the file does not exist, an empty file 92 [self. stream open]; 93} 94 95-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data 96 {97 // write data 98/* 99 first parameter: the second parameter of data to be written: 100 x/101 [self. stream write: data. bytes maxLength: data. length]; 103 104 105 // 3. the size of the currently downloaded data is accumulated by 106 self. currentSzie + = data. length; 107 108 // 4. the file download progress is calculated as 109 NSLog (@ "% f", 1.0 * self. currentSzie/self. totalSzie); 110 111 self. progressView. progress = 1.0 * self. currentSzie/self. totalSzie; 112} 113 114-(void) connectionDidFinishLoading :( NSURLConnection *) connection115 {116 NSLog (@ "% @", self. fullPath); 117 118 // 1. disable output stream 119 [self. stream close]; 120 121 // 2. clear the pointer 122 self. stream = nil; 123} 124 125-(void) connection :( NSURLConnection *) connection didFailWithError :( NSError *) error126 {127} 128 129 @ end

 

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.