参照网上的例子做的一次总结 切实可行
.h文件中
创建一个进度条,由ASI托管,添加开始和暂停两个事件
#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
@interface ViewController : UIViewController<ASIHTTPRequestDelegate,ASIProgressDelegate>
{
UIProgressView * _progressView;
}
@property (nonatomic,retain) UIProgressView* progressView;
@property (nonatomic,retain) ASINetworkQueue * asiNetQueue;
@property (nonatomic,retain) ASIHTTPRequest * asiHttpRequest;
- (IBAction)startClick:(id)sender;
- (IBAction)pauseClick:(id)sender;
.m文件中
@synthesize progressView=_progressView;
@synthesize asiNetQueue=_asiNetQueue;
@synthesize asiHttpRequest=_asiHttpRequest;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
_progressView=[[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
_progressView.frame=CGRectMake(10, 100, 300, 0);
_progressView.progress=0.0f;
[self.view addSubview:_progressView];
[_progressView release];
_asiNetQueue=[[ASINetworkQueue alloc] init];//开启队列
[_asiNetQueue reset];//nil
_asiNetQueue.showAccurateProgress=YES;
[_asiNetQueue go];
}
//开始下载事件:
- (IBAction)startClick:(id)sender {
NSURL * url=[NSURL URLWithString:@"http://fdfs.xmcdn.com/group1/M00/24/5E/wKgDrVH26tnQ3MJWAJJPLsXTccM542.mp3"];
_asiHttpRequest=[ASIHTTPRequest requestWithURL:url];
_asiHttpRequest.delegate=self;
_asiHttpRequest.downloadProgressDelegate=self;
//保存路径
NSString * savePath=[NSHomeDirectory() stringByAppendingPathComponent:@"test.mp3"];
//临时路径,开在开始后,先将已下载的数据存在临时文件中,任务完成后,将临时文件拷贝到 savePath
NSString * temp=[NSHomeDirectory() stringByAppendingPathComponent:@"temp"];
NSString * tempPath=[temp stringByAppendingPathComponent:@"test.mp3"];
NSLog(@"%@",temp);
//创建文件管理器
NSFileManager * fileManager=[NSFileManager defaultManager];
//判断temp文件夹是否存在,如果没有 创建
BOOL fileExist=[fileManager fileExistsAtPath:temp];
if (!fileExist) {
[fileManager createDirectoryAtPath:temp withIntermediateDirectories:YES attributes:nil error:nil];
}
[_asiHttpRequest setDownloadDestinationPath:savePath];
[_asiHttpRequest setTemporaryFileDownloadPath:tempPath];
_asiHttpRequest.allowResumeForFileDownloads=YES;
[_asiHttpRequest setDownloadProgressDelegate:self];
//给当前请求设置一个标示,便于队列中有多个下载任务时 找到当前下载任务
[_asiHttpRequest setUserInfo:[NSDictionary dictionaryWithObject:[NSNumber numberWithInt:100] forKey:@"downLoadID"]];
//加入队列
[_asiNetQueue addOperation:_asiHttpRequest];
}
//暂停下载
- (IBAction)pauseClick:(id)sender {
for (ASIHTTPRequest *request in [_asiNetQueue operations]) {
//查看userinfo信息
NSInteger downLoadID = [[request.userInfo objectForKey:@"downLoadID"] intValue];
if (100 == downLoadID) {
//判断ID是否匹配
//暂停匹配对象
[request clearDelegatesAndCancel];
}
}
}
//滚动条的代理方法
-(void)setProgress:(float)newProgress
{
[_progressView setProgress:newProgress];
}