// // 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