Reproduced from: http://blog.csdn.net/sirchenhua/article/details/7286312? Reload
The key to implementing resumable data transfer through nsurlconnection is to customize the range field attribute of the HTTP request header.
Range Header
The range header field can request one or more sub-ranges of an object. For example,
Indicates the first 500 Bytes: bytes = 0-499
Indicates the second 500 Bytes: bytes = 500-999
Indicates the last 500 Bytes: bytes =-500
Indicates the range after 500 Bytes: bytes = 500-
First and last Bytes: bytes = 0-0,-1
Specify the following ranges: bytes = 500-600,601-999.
However, the server can ignore this request header. If the unconditional get contains the range request header, the response will be returned with the status code 206 (partialcontent) instead of 200 (OK ).
Use nsmutableurlrequest in IOS to define the header domain
-
- Nsurl * url1 = [nsurl urlwithstring :@"";
-
- Nsmutableurlrequest * request1 = [nsmutableurlrequest requestwithurl: url1];
- [Request1 setvalue :@"Bytes = 20000 -"Forhttpheaderfield :@"Range"];
-
- [Request1 setcachepolicy: nsurlrequestreloadignoringlocalcachedata];
-
- Nsdata * returndata1 = [nsurlconnection sendsynchronousrequest: request1 returningresponse: Nil error: Nil];
-
- [Self writetofile: returndata1 filename :@"Somepath"];
-
-
-
-
- -(Void) Writetofile :( nsdata *) Data filename :( nsstring *) filename
-
- {
-
- Nsstring * filepath = [nsstring stringwithformat :@"% @", Filename];
-
- If([[Nsfilemanager defaultmanager] fileexistsatpath: filepath] = No ){
-
- Nslog (@"File not exist, create it ...");
- [[Nsfilemanager defaultmanager] createfileatpath: filepath contents: Nil attributes: Nil];
-
- }Else{
-
- Nslog (@"File exist !!! ");
-
- }
-
-
- File* File = fopen ([filename utf8string], [@"AB +"Utf8string]);
-
- If(File! = NULL ){
-
- Fseek (file, 0, seek_end );
-
- }
-
- IntReadsize = [Data Length];
-
- Fwrite ((Const Void*) [Data bytes], readsize, 1, file );
-
- Fclose (File );
-
- }