//
// ViewController.m
// UrlSession
//
// Created by dc0061 on 15/12/10.
// Copyright © 2015年 dc0061. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
{
UILabel *_url;
UILabel *tishi;
UITextField *_urlName;//输入框,输入url
UIImageView *_image;
//添加按钮
UIButton *_xiazai;
UIButton *_quxiao;
UIButton *_guaqi;
UIButton *_huifu;
UIProgressView *pro;//进度条
NSURLSessionDownloadTask *_download;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self layout];
}
//加载控件
- (void) layout{
_url= [[UILabel alloc]initWithFrame:CGRectMake(40, 50, 50, 40)];
_url.text=@"网址";
_url.textColor=[UIColor redColor];
[self.view addSubview:_url];
_urlName=[[UITextField alloc]initWithFrame:CGRectMake(100, 50, 250, 40)];
_urlName.borderStyle=UITextBorderStyleRoundedRect;//设置边框样式
_urlName.text=@"http://dlsw.baidu.com/sw-search-sp/soft/2a/25677/QQ_V4.0.5.1446465388.dmg";
// _urlName.text=@"http://img15.3lian.com/2015/f2/52/d/45.jpg";
[self.view addSubview:_urlName];
_image=[[UIImageView alloc]initWithFrame:CGRectMake(40, 120, 300, 400)];
_image.image=[UIImage imageNamed:@"2"];
[self.view addSubview:_image];
pro=[[UIProgressView alloc]initWithFrame:CGRectMake(40, 570, 200, 20)];
[self.view addSubview:pro];
tishi=[[UILabel alloc]initWithFrame:CGRectMake(250, 550, 100, 40)];
tishi.font=[UIFont systemFontOfSize:10];
tishi.text=@"正在下载。。。";
tishi.textColor=[UIColor redColor];
[self.view addSubview:tishi];
_dowenloadFile=[[UIButton alloc]initWithFrame:CGRectMake(20, 600, 80, 50)];
[_dowenloadFile setTitle:@"简化下载" forState:UIControlStateNormal];
[_dowenloadFile setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[_dowenloadFile addTarget:self action:@selector(dowenloadFile) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_dowenloadFile];
_xiazai=[[UIButton alloc]initWithFrame:CGRectMake(110, 600, 50, 50)];
[_xiazai setTitle:@"下载" forState:UIControlStateNormal];
[_xiazai setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[_xiazai addTarget:self action:@selector(xiazai) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_xiazai];
_quxiao=[[UIButton alloc]initWithFrame:CGRectMake(170, 600, 50, 50)];
[_quxiao setTitle:@"取消" forState:UIControlStateNormal];
[_quxiao setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[_quxiao addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_quxiao];
_guaqi=[[UIButton alloc]initWithFrame:CGRectMake(230, 600, 50, 50)];
[_guaqi setTitle:@"挂起" forState:UIControlStateNormal];
[_guaqi setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[_guaqi addTarget:self action:@selector(guaqi) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_guaqi];
_huifu=[[UIButton alloc]initWithFrame:CGRectMake(290, 600, 50, 50)];
[_huifu setTitle:@"恢复" forState:UIControlStateNormal];
[_huifu setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[_huifu addTarget:self action:@selector(huifu) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_huifu];
}
- (void) xiazai{
NSLog(@"下载");
//创建一个URL
NSString *urlstr=_urlName.text;
urlstr=[urlstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSURL *url=[NSURL URLWithString:urlstr];
//创建请求
NSURLRequest *request=[NSURLRequest requestWithURL:url];
//创建session: NSURLSessionConfiguration配置session (默认会话 单例)
NSURLSessionConfiguration *sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfig.timeoutIntervalForRequest=20;//请求超时时间
// sessionConfig.timeoutIntervalForResource=20;//资源超时时间
//是否允许蜂窝网络下载(2G/3G/4G) NO: 只能在WiFi的情况下下载
sessionConfig.allowsCellularAccess=YES;
//创建会话 指定配置和代理
NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
_download=[session downloadTaskWithRequest:request];
//恢复任务
[_download resume];
}
- (void) quxiao{
NSLog(@"取消");
[_download cancel];
}
- (void) guaqi{
NSLog(@"挂起");
[_download suspend];
}
- (void) huifu{
NSLog(@"恢复");
[_download resume];
}
//更新进度条
- (void) setprogress : (int64_t)totalBytesWritten :(int64_t) totalBytesExpectedToWrite{
//异步处理进程 (dispatch_get_main_queue())获取主队列
dispatch_async(dispatch_get_main_queue(), ^{
pro.progress=(float)totalBytesWritten/totalBytesExpectedToWrite;
if (pro.progress==1) {
tishi.text=@"下载完成";
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;//屏幕左上角的菊花
}else{
[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
}
});
}
//后面三个参数代表:当前下载量,总的下载量,下载文件的总大小
#pragma mark 下载中会多次调用,可以用来记录进度条 这个是代理中的方法
- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
[self setprogress:totalBytesWritten :totalBytesExpectedToWrite];//更新进度条
}
#pragma mark 下载完成会调用的方法
- (void)URLSession:(NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location{
NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
path=[path stringByAppendingPathComponent:@"qq1.dmg"];
NSURL *saveUrl=[NSURL fileURLWithPath:path];//转换成本地的url使用 fileURLWithPath
//复制文件,从location 拷贝到我想要的位置
NSError *error;
[[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&error];
if(error){
NSLog(@"error : %@",error.localizedDescription);
}
}
#pragma mark 不管下载成功与否,都会调用
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
if (error) {
NSLog(@"error : %@", error.localizedDescription);
}else{
NSLog(@"无错误");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
@end
转载于:https://my.oschina.net/u/2287505/blog/544608