An analysis of IOS HTTP breakpoint continuous transmission

Source: Internet
Author: User

Download Lofter Client
An analysis of IOS HTTP breakpoint continuous transmission

The key to HTTP implementation of a breakpoint is to add a "Range" header to the HttpRequest.

Set range header, value: bytes=x-y;x: Start Byte, y: End byte, not specified as end of file
[Request addvalue:@ "bytes=500-" forhttpheaderfield:@ "Range"];

If the server responds correctly, it can be successfully resumed, and if the server does not support it, it will only be used in other ways.

After testing, the server is not supported in two situations:

1. No response at all

If not processed, the file cannot be downloaded.

Test Address: HTTP://DL_DIR.QQ.COM/QQFILE/QQ/QQFORMAC/QQ_V2.4.2.DMG

After sending the request, it went directly into the delegate of Didfailwitherror, and the error message was time out.

The processing that can be done for this situation is to add a flag that supports the continuation of the breakpoint.

Specific:

The first request, the start byte is 0, does not send the range header, can download normally;

When the download is interrupted, the second request starts, the start byte is not 0, and the range header is sent;

If you enter the delegate of Didfailwitherror, it is indicated that this link can not be resumed by a breakpoint, the cache is cleared before each request, the byte starting is guaranteed to be 0, and the range header is not sent.

2. Regardless of the value of the Send range, the server will be re-downloaded.

Failure to process will result in an error in the file being passed.

Test Address: Https://github.com/CocoaPods/CocoaPods/archive/master.zip

The treatment scenario for this scenario is:

When the response is first received, the total size of the file is recorded;

Each time after receiving a response to compare the download length and total size is not the same;

If it is the same and there is a cache, that is the case; Delete the cache directly and re-download it.

The following is an example of using Nsurlconnection to implement HTTP breakpoint continuation:

For the above two types of simple processing, the callback function has yet to be added

MXDownload.h file:

#import <Foundation/Foundation.h>

@interface Mxdownload:nsobject

File name path
@property (nonatomic, readonly) NSString *filepath;

Whether a flag is being downloaded
@property (nonatomic, readonly) BOOL downloading;

Initialization
-(ID) initwithurlstring: (NSString *) urlstring;

Two states
-(void) start;
-(void) stop;

Clear Cache
-(void) ClearCache;

@end

MXDOWNLOAD.M file:

#import "MXDownload.h"
#import "Nsstring+mx.h"

#define File_info_plist [NSString pathwithname:@ "Mxdownload/fileinfo.plist" directory:nscachesdirectory]

@interface Mxdownload () {
Nsurlconnection *_urlconnection;
NSString *_urlstring;
BOOL _downloading,_didaddrange,_shouldresume;

NSString *_filename,*_filepath, *_tempfilepath;
Nsfilehandle *_filehandle;
unsigned long long _fileoffset,_filesize;
}

@end

@implementation Mxdownload
@synthesize downloading = _downloading;
@synthesize FilePath = _filepath;

//Initialize, by the way set download file and download temporary file path
-(ID) initwithurlstring: (NSString *) urlstring{
    self = [super INIT];
    if (self) {
        _urlstring = urlstring;
        _shouldresume = YES;
        if (_urlstring) {
             _filename = [_urlstring MD5];
            _filepath = [NSString pathwithname:[ NSString stringwithformat:@ "mxdownload/%@", _filename] directory:nscachesdirectory];
            _tempfilepath = [NSString stringWithFormat: @ "%@.temp", _filepath];
       }
   }
    return self;
}

Start download
-(void) start{
If you are downloading, interrupt
if (_downloading) return;
No URL, also interrupt
if (!_urlstring) return;

Temporary file handle
_filehandle = [Nsfilehandle Filehandleforwritingatpath:_tempfilepath];
Gets the location where the download of this request started, if the file does not exist, is 0
_fileoffset = _filehandle? [_filehandle Seektoendoffile]: 0;

Initializing requests
Nsmutableurlrequest *request = [[Nsmutableurlrequest alloc] Initwithurl:[nsurl urlwithstring:_urlstring]];
It is important to set the caching policy, because the files are stored on their own, regardless of the cache, so the cache is ignored
Otherwise, the second request will go wrong.
[Request Setcachepolicy:nsurlrequestreloadignoringlocalcachedata];

Most critical place, set range header, value: bytes=x-y;x: Start Byte, y: End byte, not specified as end of file
_didaddrange = NO;
if (_fileoffset! = 0 && _shouldresume) {
[Request addvalue:[nsstring stringwithformat:@ "bytes=%llu-", _fileoffset] forhttpheaderfield:@ "Range"];
_didaddrange = YES;
}

_urlconnection = [[Nsurlconnection alloc] initwithrequest:request delegate:self];
[_urlconnection start];

_downloading = YES;
}

End Download
-(void) stop{
[_urlconnection Cancel];
_urlconnection = nil;
[_filehandle CloseFile];
_downloading = NO;
}

Purge files
-(void) clearcache{
if (_downloading) [self stop];
[[Nsfilemanager Defaultmanager] Removeitematpath:_filepath Error:nil];
[[Nsfilemanager Defaultmanager] Removeitematpath:_tempfilepath Error:nil];
}

#pragma mark-
#pragma Mark Nsurlconnectiondelegate

Receive a response
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response{
File size for this request back
Long Long filelength = response.expectedcontentlength;
if (filelength = = nsurlresponseunknownlength) [self stop];

NSData *existfiledata = [[NSData alloc] initwithcontentsoffile:_filepath];

Check whether the file has been downloaded and completed
if (existfiledata && existfiledata.length = = filelength) {
NSLog (@ "already downloaded");
[Self stop];
}
else{
Total size of saved files
if (!_didaddrange) {
Nsmutabledictionary *dic = [Nsmutabledictionary new];
[DiC addentriesfromdictionary:[nsdictionary dictionarywithcontentsoffile:file_info_plist];
[dic Setvalue:[nsnumber Numberwithlonglong:filelength] forkey:_filename];
[DiC writetofile:file_info_plist Atomically:yes];
}

Nsfilemanager *filemanager = [Nsfilemanager Defaultmanager];
Erase the old files first
[FileManager Removeitematpath:_filepath Error:nil];

       //If the size of this request is equal to the total size of the file and the temporary file exists, delete the temporary file
        //Resolve each request to start again
        nsdictionary *dic = [ Nsdictionary Dictionarywithcontentsoffile:file_info_plist];
        BOOL istotallength = Filelength = = [[dic valueforkey:_filename] Longlongvalue];
        if ([FileManager Fileexistsatpath:_tempfilepath] && Istotallength) {
            [FileManager Removeitematpath:_tempfilepath Error:nil];
       }

Re-create the file
if (![ FileManager Fileexistsatpath:_tempfilepath]) {
[FileManager Createfileatpath:_tempfilepath Contents:nil Attributes:nil];
_filehandle = [Nsfilehandle Filehandleforwritingatpath:_tempfilepath];
_fileoffset = 0;
}

_filesize = Filelength + _fileoffset;

Use _fileoffset to check whether to re-download or continue downloading
NSLog (@ "%@", _fileoffset @ "continue download": @ "start download");
}
}

Constantly receiving data
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) adata{
Write file
[_filehandle Writedata:adata];
_fileoffset = [_filehandle offsetinfile];
NSLog (@ "Download progress:%lld/%lld", _fileoffset,_filesize);
}

-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error{
[Self stop];
If you do not continue to pass, delete the temporary file and try again
if (_shouldresume) {
_shouldresume = NO;
[[Nsfilemanager Defaultmanager] Removeitematpath:_tempfilepath Error:nil];
[Self start];
}
}

Complete
-(void) connectiondidfinishloading: (nsurlconnection *) connection{
[[Nsfilemanager Defaultmanager] Moveitematpath:_tempfilepath topath:_filepath Error:nil];
NSLog (@ "Download complete");
[Self stop];
}

@end

Call:

-(Ibaction) Startdownload: (ID) sender{
if (_downloader = = nil) {
_downloader = [[Mxdownload alloc] initwithurlstring:@ "Https://github.com/CocoaPods/CocoaPods/archive/master.zip" ];
_downloader = [[Mxdownload alloc] initwithurlstring:@ "HTTP://DL_DIR.QQ.COM/QQFILE/QQ/QQFORMAC/QQ_V2.4.2.DMG"];
_downloader = [[Mxdownload alloc] initwithurlstring:@ "Http://192.168.50.19:8080/vcont/wb.mp3"];
}
if (_downloader.downloading) {
[_downloader stop];
}
else{
[_downloader start];
}
}

An analysis of IOS HTTP breakpoint continuous transmission

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.