//
// ViewController.m
// 多线程下载练习
//
// Created by dc0061 on 15/12/24.
// Copyright © 2015年 dc0061. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()<NSURLSessionDownloadDelegate>
{
NSMutableArray *_proArray;
UILabel *_label;
UILabel *_strUrl;
UIButton *_down;
UIProgressView *_pro;
NSURLSessionDownloadTask *_download;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self layout];
}
- (void) layout{
_proArray=[NSMutableArray array];
for (int i=0; i<4; i++) {
_label = [[UILabel alloc]initWithFrame:CGRectMake(20, 50+120*i, 40, 50)];
_label.text=@"地址:";
[self.view addSubview:_label];
_strUrl = [[UILabel alloc]initWithFrame:CGRectMake(70, 50+120*i, 275, 70)];
_strUrl.text=@"http://dlsw.baidu.com/sw-search-sp/soft/2a/25677/QQ_V4.0.5.1446465388.dmg";
_strUrl.numberOfLines=3;
[self.view addSubview:_strUrl];
_pro = [[UIProgressView alloc]initWithFrame:CGRectMake(70, 150+120*i, 275, 70)];
_pro.tag=i;
[self.view addSubview:_pro];
[_proArray addObject:_pro];
_down = [[UIButton alloc]initWithFrame:CGRectMake(50, 500, 275, 70)];
[_down setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[_down setTitle:@"下载" forState:UIControlStateNormal];
[_down addTarget:self action:@selector(download) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_down];
}
}
- (void) download{
//创建一个对列
dispatch_queue_t globalQueue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
//创建多个线程
for (int i=0; i<4; i++) {
//异步执行任务
dispatch_async(globalQueue, ^{
[self load:i];
});
}
}
- (void) load :(int) index{
//获取主线程
dispatch_queue_t mainQueue=dispatch_get_main_queue();
//创建下载任务
dispatch_sync(mainQueue, ^{
[self beginDownload:index];
});
}
- (void) beginDownload : (int) index{
NSString *urlStr=_strUrl.text;
//将获取到的字符串进行先进行编码
urlStr=[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL*url=[NSURL URLWithString:urlStr];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest=20.0;// 请求超时时间
NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
_download=[session downloadTaskWithRequest:request];
_download.taskDescription=[NSString stringWithFormat:@"%i",index];//增加一个任务描述
//启动任务
[_download resume];
NSLog(@"下载中");
}
//后面三个参数代表:当前下载量,总的下载量,下载文件的总大小
#pragma mark 下载中会多次调用,可以用来记录进度条 这个是代理中的方法
- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
int task=[downloadTask.taskDescription intValue];
// 更新UI 需要在主线程里面进行
dispatch_sync(dispatch_get_main_queue(), ^{
((UIProgressView *)_proArray[task]).progress=(float)totalBytesWritten/(float)totalBytesExpectedToWrite;
});
}
#pragma mark 下载完成后调用的方法
- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
//获取缓存目录
NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"%@",path);
path=[path stringByAppendingPathComponent:[NSString stringWithFormat:@"%@QQ_V4.0.5.1446465388.dmg",downloadTask.taskDescription]];
NSURL *saveUrl=[NSURL fileURLWithPath:path];
//将文件复制到指定目录
[[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:nil];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end