// // ViewController.m // 網絡編程3 // // Created by DC017 on 15/12/10. // Copyright © 2015年 DC017. All rights reserved. // #pragma mark NSURLSession 學習 #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> { UITextField * textfield; UIButton * xiazai; UIButton * quxiao; UIButton * zanting; UIButton * huifu; UILabel * label; UIProgressView * progress; NSURLSessionDownloadTask *downloadTask; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layout]; // Do any additional setup after loading the view, typically from a nib. } //layout佈局 -(void)layout{ textfield=[[UITextField alloc]initWithFrame:CGRectMake(20, 60, 300, 20)]; textfield.layer.borderWidth=1; textfield.layer.borderColor=[UIColor redColor].CGColor; textfield.text=@"http://b.zol-img.com.cn/desk/bizhi/image/5/2560x1600/1414029841427.jpg"; //設置圓角 textfield.layer.cornerRadius=4; [self.view addSubview:textfield]; label=[[UILabel alloc]initWithFrame:CGRectMake(60, 200, 80, 20)]; label.textColor=[UIColor redColor]; [self.view addSubview:label]; progress =[[UIProgressView alloc]initWithFrame:CGRectMake(20, 100,300 ,5)]; [self.view addSubview:progress]; xiazai=[[UIButton alloc]initWithFrame:CGRectMake(20, 400, 60, 20)]; zanting=[[UIButton alloc]initWithFrame:CGRectMake(100, 400, 60, 20)]; huifu=[[UIButton alloc]initWithFrame:CGRectMake(180, 400, 60, 20)]; quxiao=[[UIButton alloc]initWithFrame:CGRectMake(260, 400, 60, 20)]; [xiazai setTitle:@"下載" forState:UIControlStateNormal]; [zanting setTitle:@"暫停" forState:UIControlStateNormal]; [huifu setTitle:@"恢復" forState:UIControlStateNormal]; [quxiao setTitle:@"取消" forState:UIControlStateNormal]; [xiazai setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [zanting setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [huifu setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [quxiao setTitleColor:[UIColor redColor] forState:UIControlStateNormal]; [xiazai addTarget:self action:@selector(xiazai) forControlEvents:UIControlEventTouchUpInside]; [zanting addTarget:self action:@selector(zanting) forControlEvents:UIControlEventTouchUpInside]; [huifu addTarget:self action:@selector(huifu) forControlEvents:UIControlEventTouchUpInside]; [quxiao addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:xiazai]; [self.view addSubview:zanting]; [self.view addSubview:huifu]; [self.view addSubview:quxiao]; } -(void)xiazai{ NSLog(@"下載"); //建立url NSString * strurl=textfield.text; strurl =[strurl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]; NSURL *url=[NSURL URLWithString:strurl]; //建立請求 NSURLRequest * request=[NSURLRequest requestWithURL:url]; //建立session 會話 //配置session(默認--單例) NSURLSessionConfiguration * sessionConfig=[NSURLSessionConfiguration defaultSessionConfiguration]; sessionConfig.timeoutIntervalForRequest=10.0f;//請求時間 sessionConfig.allowsCellularAccess=YES;//是否容許蜂窩網絡下載(2g,3g,4g) //建立會話 NSURLSession *session=[NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理 downloadTask =[session downloadTaskWithRequest:request]; [downloadTask resume]; } -(void)zanting{ NSLog(@"暫停"); [downloadTask suspend]; [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; } -(void)huifu{ NSLog(@"恢復"); [downloadTask resume]; if ([label.text isEqualToString:@""]) { [UIApplication sharedApplication].networkActivityIndicatorVisible=YES; }else{ [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; } } -(void)quxiao{ NSLog(@"取消"); progress.progress=0; [downloadTask cancel]; [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; label.text=nil; } -(void)setjindutiaozhuangtai:(int64_t)zongliang setjindutiao:(int64_t)dangqianxiazailiang{ //異步 dispatch_async(dispatch_get_main_queue(), ^{ progress.progress=(float)dangqianxiazailiang/zongliang; if (dangqianxiazailiang==zongliang) { label.text=@"下載完成"; [UIApplication sharedApplication].networkActivityIndicatorVisible=NO; } else{ label.text=@"正在下載"; [UIApplication sharedApplication].networkActivityIndicatorVisible=YES; } }); } #pragma mark 下載任務代理 #pragma mark 下載中() - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ [self setjindutiaozhuangtai:totalBytesExpectedToWrite setjindutiao:totalBytesWritten]; NSLog(@"bytesWritten: %lld totalBytesWritten:%lld totalBytesExpectedToWrite:%lld ",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite); } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark 下載完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ NSString *path=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; path=[path stringByAppendingPathComponent:@"圖片01.jpg"]; NSLog(@" 緩存路徑 %@",path); NSURL * saveUrl=[NSURL fileURLWithPath:path]; NSLog(@" %@",saveUrl); //關鍵:複製文件,從location——》saveUrl NSError * error; [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&error]; if (error) { NSLog(@"錯誤:%@",error); } } -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ if (error) { NSLog(@"%@",error); } } @end