您的位置:首页 > 理论基础 > 计算机网络

IOS成长之路-ASIHTTPRequest 断点续传

2014-12-31 23:49 405 查看
1.导入ASIHTTPRequest第三方类库



下载地址:ASIHttpRequest类库 完整代码下载:下载

2.在 .h 文件中

[cpp] view plaincopy

#import <UIKit/UIKit.h>

#import "ASIHTTPRequest.h"

#import "ASINetworkQueue.h"

@interface DownLoadViewController : UIViewController<ASIHTTPRequestDelegate>

{

UIProgressView *_progressView;

}

@property(nonatomic, retain) UIProgressView *progressView;

@property(nonatomic, retain) ASINetworkQueue *asiQueue;

@property(nonatomic, retain) ASIHTTPRequest *asiHttpRequest;

@end

3.在 .m 文件中 实现这一过程

首先开启队列:

[cpp] view plaincopy

_asiQueue=[[ASINetworkQueue alloc]init];//开启队列

[_asiQueue reset];//nil

_asiQueue.showAccurateProgress=YES;//进度

[_asiQueue go];

实现下载:

[cpp] view plaincopy

NSURL *url = [NSURL URLWithString:@"请求地址"];

_asiHttpRequest=[ASIHTTPRequest requestWithURL:url];

_asiHttpRequest.delegate=self;

_asiHttpRequest.downloadProgressDelegate=self;//下载进度的代理,用于断点续传

path = NSHomeDirectory();//该方法得到的是应用程序目录的路径

//目的路径,设置一个目的路径用来存储下载下来的文件

NSString *savePath = [path stringByAppendingPathComponent:@"qgw.mp3"];

/*

临时路径:

1.设置一个临时路径用来存储下载过程中的文件

2.当下载完后会把这个文件拷贝到目的路径中,并删除临时路径中的文件

3.断点续传:当设置断点续传的属性为YES后,每次执行都会到临时路径中寻找要下载的文件是否存在,下载的进度等等。。。然后就会在此基础上继续下载,从而实现续传的效果

设置临时路径在这个过程中是相当重要的。。。

*/

NSString *temp = [path stringByAppendingPathComponent:@"temp"];

/*

又在临时路径中添加了一个mp3格式的文件,这就相当于设置了一个假的要下载的文件,其实是不存在的,可以这么理解:这里提供了一个容器,下载的内容填充到了这个容器中。

这个容器是必须要设置的,要不然它会不知道要下载到什么里面。。。

会有人说:问什么不和上面的临时路径拚在一起,不是一样么:NSString *temp = [path stringByAppendingPathComponent:@"temp/qgw.mp3"];

这是不行的,因为你的临时路径必须要保证是正确的、是拥有的,所以在下面你要用NSFileManager来判断是否存在这么一个路径,如果不存在就去创建,

当你创建的时候会把qgw.mp3当作是一个文件夹来创建的,所以每次断点续传的时候都会进入到qgw.mp3这个文件夹中寻找,当然是找不到的(因为qwg.mp3就是)

so,要分开来写。。。

*/

NSString *tempPath = [temp stringByAppendingPathComponent:@"qgw.mp3"];

//创建文件管理器

NSFileManager *fileManager = [NSFileManager defaultManager];

//判断temp文件夹是否存在

BOOL fileExists = [fileManager fileExistsAtPath:temp];

if (!fileExists)

{//如果不存在则创建,因为下载时,不会自动创建文件夹

[fileManager createDirectoryAtPath:temp

withIntermediateDirectories:YES

attributes:nil

error:nil];

}

[ _asiHttpRequest setDownloadDestinationPath:savePath ];//下载路径

[ _asiHttpRequest setTemporaryFileDownloadPath:tempPath ];//临时路径,一定要设置临时路径。。

_asiHttpRequest.allowResumeForFileDownloads = YES;//打开断点,是否要断点续传

//进度条

_progressView.alpha = 1.0f;

_progressView.progress=0;//赋值为0

[_asiQueue addOperation:_asiHttpRequest];//加入队列

得到下载的进度:

[cpp] view plaincopy

//代理方法,得到下载进度

- (void)setProgress:(float)newProgress{

[_progressView setProgress:newProgress];//赋给进度条

}

停止下载:

[cpp] view plaincopy

[_asiHttpRequest clearDelegatesAndCancel];//停掉
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: