Nsurlconnection realization of the breakpoint continuous transmission

Source: Internet
Author: User
Tags md5 encryption

What about this? West: Range header field The range Header field can request an entity's? One or more child scopes.

For example, table, header 500 bytes: bytes=0-499

Table? Two x 500 bytes: bytes=500-999

Table showing the last 500 bytes: bytes=-500

Table shows the range after 500 bytes: bytes=500-

First and last? One byte: bytes=0-0,-1

Specify at the same time? Several ranges: bytes=500-600,601-999
To implement a breakpoint download is to add the Range header to the HttpRequest.
[Request addvalue:@ "bytes=500-" forhttpheaderfield:@ "Range"];
? As to whether the normal implementation of the continuation of the breakpoint, but also to see if the server support. If there is support, everything is fine. If not? There are two possible scenarios for support, 1. Ignore your range value, each time
New download data; 2. Direct download failed.

The process is as follows
1. Download to save to the local sandbox, so first to get the full path in the Shahe, (the file is saved in the sandbox documents/%@) in order to get the file size of the offensive download
MD5 encryption, a data encryption tool, is a hash function widely used in the field of computer security to provide integrity protection of messages. Md5hash, the hash value calculator, is a MD5 verification tool. Each file can be calculated with a hash MD5 verification program to a fixed MD5 code.
Get the full path in the sandbox
-(NSString *) Getfullfilepathwithurl: (NSString *) urlname {
NSString * name = [urlname Md5hash];
Get the path in the sandbox
NSString *path = [Nshomedirectory () stringbyappendingformat:@ "/documents/%@", name];
return path;
}
Determine if there is no such file to get the size without creating this file

BOOL isexist = [[Nsfilemanager Defaultmanager] fileexistsatpath:filepath];
if (!isexist) {
self.loadedsize = 0;
Create a new empty file without
[[Nsfilemanager Defaultmanager] Createfileatpath:filepath contents:nil Attributes:nil];
}else {
Have to get the file size that has been downloaded
Nsdictionary *filedict = [[Nsfilemanager Defaultmanager] Attributesofitematpath:filepath Error:nil];
Self.loadedsize = filedict.filesize;
}
Open File
_filehandle = [Nsfilehandle Filehandleforupdatingatpath:filepath];

Send a download request
Nsmutableurlrequest *request = [nsmutableurlrequest requestwithurl:[nsurl urlwithstring:url];
Breakpoint download should tell the server which byte to start downloading
By requesting the hair to the server (the prerequisite server must support a breakpoint to continue the transmission)
Add Request Header Range header
[Request addvalue:[nsstring stringwithformat:@ "bytes=%llu-", Self.loadedsize] forhttpheaderfield:@ "Range"];
Start a thread to request a download
_connection = [[Nsurlconnection alloc] initwithrequest:request delegate:self];

Compliance Agreement
#pragma mark-nsurlconnectiondatadelegate
The server responds to the client
-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) Response {
The server tells the client to send the data and will tell the sending size (the size of the file remaining)
NSLog (@ "Len:%llu", response.expectedcontentlength);
Calculate Total File Size
Self.filesize = Self.loadedsize+response.expectedcontentlength;
}
Callback when the service sends data
A paragraph sent
-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) Data {
The download process will write data to the local sandbox
[_filehandle seektoendoffile];//positioning to end of file
[_filehandle Writedata:data];
[_filehandle synchronizefile];//sync to disk
File already downloaded size
Self.loadedsize + = Data.length;

Callback block to pass size to each other
if (Self.myblock) {
Self.myblock (self); ************block The key marker is here to pass the value ***************
}
}
Stop download close file
-(void) Stopdownload {
if (_connection) {
[_connection Cancel];
_connection = nil;
}
[_filehandle closefile];//Close File
}
View will be responsible for the display of the interface, considering the refresh of the interface, will use a timer to control the interface refresh,
-(void) Viewwillappear: (BOOL) Animated {
[Super viewwillappear:animated];
Get scale
Double scale = [[Nsuserdefaults standarduserdefaults] doubleforkey:kurl];
Self.slider.value = scale;
}

-(void) didreceivememorywarning {
[Super didreceivememorywarning];
Dispose of any resources the can be recreated.
}
Calculation speed is called every 1s
-(void) GetSpeed {
The current downloaded size-the first 1s has been downloaded size
Self.speed = (self.loadedsize-self.preloadedsize)/1024.0;
Save
Self.preloadedsize = self.loadedsize;
}
-(Ibaction) Startclick: (ID) Sender {
if (!self.timer) {
Self.timer = [Nstimer scheduledtimerwithtimeinterval:1 target:self selector: @selector (getspeed) Userinfo:nil repeats: YES];
}

__weak typeof (self) weakself = self;

[Self.download breakpointdownloaddatawithurl:kurl downloadprocess:^ (breakpointdownload *download) {***********//block type of the value passed
Save already downloaded size
Weakself.loadedsize = download.loadedsize;

This block************************************* will be recalled during the download process.
Double fileSize = download.filesize/1024.0/1024.0;//m
Use block to pass the value *****************************
Double scale = ((double) download.loadedsize)/download.filesize;
WeakSelf.slider.value = scale;

Save this progress to the local
[[Nsuserdefaults Standarduserdefaults] Setdouble:scale Forkey:kurl];
[[Nsuserdefaults standarduserdefaults] synchronize];

if (Scale >= 1.0) {
if (Self.timer) {
[Self.timer invalidate];
Self.timer = nil;
}
Destroying timers
}
WeakSelf.label.text = [NSString stringwithformat:@ "has downloaded%.2f%% total size%.2fm speed%.2fkb/s", Scale*100,filesize, Weakself.speed];
}];
}
-(Ibaction) Stopclick: (ID) Sender {
if (Self.timer) {
[Self.timer invalidate];
Self.timer = nil;
}
[Self.download Stopdownload];
}
Summarize
1. First go to the sandbox to find the file, open the file. (_filehandle = [Nsfilehandle Filehandleforupdatingatpath:filepath]) Get the file size that has been downloaded
2. The breakpoint continues to transmit, to splice requests to increase the request header range header, let the server know where to start the download, so called the breakpoint continued to pass
3. Starting the download invokes the Protocol method and begins to return the data to the view via the block callback,
4.View interface display data, by invoking the download method (containing block), the download process through the value returned by the block to the interface output data,
5. Enable timer, refresh interface, display data
6. When the download is stopped, the timer is first destroyed and then the Nsurlconnection Cancel Request link ([_connection Cancel]) closes the file

Nsurlconnection realization of the breakpoint continuous transmission

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.