IOS download feature: Breakpoint Download (pause and start) (Nsurlconnectiondatadelegate method)

Source: Internet
Author: User

1,model File Code

File name: HMFileDownloader.h

#import <Foundation/Foundation.h>

@interface Hmfiledownloader:nsobject

/**

* The remote URL of the file you want to download (the path to the connection server)

*/

@property (nonatomic, copy) NSString *url;

/**

* File storage path (where files are downloaded)

*/

@property (nonatomic, copy) NSString *destpath;

/**

* is downloading (there is no download, only the inside of the downloader to know)

*/

@property (Nonatomic, readonly, getter = isdownloading) BOOL downloading;

/**

* To monitor the download progress

*/

@property (nonatomic, copy) void (^progresshandler) (double progress);

/**

* To listen to the download complete

*/

@property (nonatomic, copy) void (^completionhandler) ();

/**

* Used to listen for download failure

*/

@property (nonatomic, copy) void (^failurehandler) (Nserror *error);

/**

* Start (Resume) Download

*/

-(void) start;

/**

* Pause Download

*/

-(void) pause;

@end

File name: HMFILEDOWNLOADER.M

#import "HMFileDownloader.h"

@interface Hmfiledownloader () <NSURLConnectionDataDelegate>

/**

* Connection Object

*/

@property (nonatomic, strong) nsurlconnection *conn;

/**

* File handle for writing data

*/

@property (nonatomic, strong) Nsfilehandle *writehandle;

/**

* Length of the currently downloaded data

*/

@property (nonatomic, assign) long long currentlength;

/**

* Total length of the full file

*/

@property (nonatomic, assign) long long totallength;

@end

@implementation Hmfiledownloader

/**

* Start (Resume) Download

*/

-(void) Start

{

Nsurl *url = [Nsurl URLWithString:self.url];

The default is a GET request

Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];

Set Request header information

NSString *value = [NSString stringwithformat:@ "bytes=%lld-", self.currentlength];

[Request Setvalue:value forhttpheaderfield:@ "Range"];

Self.conn = [nsurlconnection connectionwithrequest:request delegate:self];

_downloading = YES;

}

/**

* Pause Download

*/

-(void) Pause

{

[Self.conn Cancel];

Self.conn = nil;

_downloading = NO;

}

#pragma mark-nsurlconnectiondatadelegate Proxy method

/**

* 1. When the response to the server is accepted (the server is connected) it is called

*/

-(void) connection: (Nsurlconnection *) connection didreceiveresponse: (Nsurlresponse *) response

{

#warning must judge

if (self.totallength) return;

1. Create an empty file into the sandbox

Nsfilemanager *mgr = [Nsfilemanager Defaultmanager];

The size you just created is 0 bytes.

[Mgr CreateFileAtPath:self.destPath Contents:nil Attributes:nil];

2. Create a file handle to write data

Self.writehandle = [Nsfilehandle FileHandleForWritingAtPath:self.destPath];

3. Get the full file length

Self.totallength = Response.expectedcontentlength;

}

/**

* 2. When data received to the server is called (may be called multiple times, each call will only pass part of the data)

*/

-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data

{

Cumulative length

Self.currentlength + = Data.length;

NSLog (@ "=%lld==", self.currentlength);

Show progress

Double progress = (double) self.currentlength/self.totallength;

if (Self.progresshandler) {//Pass progress value to block

Self.progresshandler (progress);

}

Move to the end of a file

[Self.writehandle Seektoendoffile];

Writes data starting at the current moving position (end of file)

[Self.writehandle Writedata:data];

}

/**

* 3. When the server's data is accepted, it is called

*/

-(void) connectiondidfinishloading: (nsurlconnection *) connection

{

Emptying attribute values

self.currentlength = 0;

self.totallength = 0;

if (self.currentlength = = self.totallength) {

Close the connection (no longer entering data into the file)

[Self.writehandle CloseFile];

Self.writehandle = nil;

}

if (Self.completionhandler) {

Self.completionhandler ();

}

}

/**

* Request error (failure) when the call (Request timeout \ Network \ No network, generally referred to as client error)

*/

-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error

{

if (Self.failurehandler) {

Self.failurehandler (Error);

}

}

@end

2. Drag the above two files to the project

3. Import in Controller file

#import "HMFileDownloader.h"

Statement

@property (nonatomic, strong) NSString *url;

@property (Retain, nonatomic) Uiprogressview *progressview;

@property (nonatomic, strong) Hmfiledownloader *filedownloader;

-(void) viewdidload

{

_progressview=[[uiprogressview Alloc]init];

_progressview.frame=cgrectmake (10, 150, 170, 20);

[Self.view Addsubview:_progressview];

[Self filedownloader];

}

-(void) Filedownloader

{

if (!_viewcont.filedownloader) {

_filedownloader = [[Hmfiledownloader alloc] init];

The file remote URL that needs to be downloaded

_filedownloader.url = @ "Http://192.168.1.9:8080/wyhouAppServices/upload/app_user/iOS%207%20Cookbook.pdf";

Where to save the file 1

NSString *caches = [Nssearchpathfordirectoriesindomains (nscachesdirectory, Nsuserdomainmask, YES) lastObject];

NSString *filepath = [Caches stringbyappendingpathcomponent:@ "20cookbook.pdf"];

Where to save the file 2

Nsurl *targeturl = [Nsurl Urlwithstring:_viewcont.filedownloader.url];

NSString *docpath = [self documentsdirectorypath];

Combine the filename and the path to the documents dir into the full path

NSString *pathtodownloadto = [NSString stringwithformat:@ "%@/%@", DocPath, [TargetUrl Lastpathcomponent]];

_filedownloader.destpath = Pathtodownloadto;

typeof (Ten) A = 20; int a = 20;

__weak typeof (self) VC = self;

_filedownloader.progresshandler = ^ (double progress) {

vc.progressview.progress=progress;

_progressview.progress = progress;

};

_filedownloader.completionhandler = ^{

NSLog (@ "------Download complete");

};

_filedownloader.failurehandler = ^ (Nserror *error) {

};

}else{

_progressview.progress= _viewcont.progressview.progress;

__weak typeof (self) VC = self;

_filedownloader.progresshandler = ^ (double progress) {

vc.progressview.progress=progress;

//

};

NSLog (@ "------");

}

return _filedownloader;

}

-(void) dealloc{

_progressview.progress=_progressview.progress;

}

Button text: "Start", "Pause"

-(void) Start {//Self.currentlength = = 200

if (_filedownloader.isdownloading) {//Pause download

[_filedownloader pause];

[_testbtn settitle:@ "Recovery" forstate:uicontrolstatenormal];

} else {//start download

[_filedownloader start];

[_testbtn settitle:@ "pause" forstate:uicontrolstatenormal];

}

}

IOS download feature: Breakpoint Download (pause and start) (Nsurlconnectiondatadelegate method)

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.