NSURLSession---------------------------- 下載記得在工程裏Info.plist中添加如下幾項(切記 切記) Xcode7.0 NSAppTransportSecurity NSAllowsArbitraryLoads Xcode7.1 App Transport Security Settings Allow Arbitrary Loads #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> { UITextField *textField; UIButton *down; UIButton *cancel; UIButton *stop; UIButton *regain; UILabel *label; UIProgressView *progress; NSURLSessionDownloadTask *downLoad; } @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self layout]; } -(void)layout{ label = [[UILabel alloc]initWithFrame:CGRectMake(20, 130, 80, 30)]; label.textAlignment = NSTextAlignmentCenter; label.layer.borderWidth = 2; label.layer.borderColor = [UIColor blackColor].CGColor; label.layer.cornerRadius = 7; progress = [[UIProgressView alloc]initWithFrame:CGRectMake(10, 90, 355, 35)]; textField = [[UITextField alloc]initWithFrame:CGRectMake(10, 30, 355, 35)]; textField.textAlignment = NSTextAlignmentCenter; textField.layer.borderWidth = 2; textField.layer.borderColor = [UIColor blackColor].CGColor; textField.layer.cornerRadius = 7; down = [[UIButton alloc]initWithFrame:CGRectMake(30, 590, 40, 30)]; [down setTitle:@"下載" forState:UIControlStateNormal]; [down setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; down.layer.borderWidth = 1; down.layer.borderColor = [UIColor blackColor].CGColor; down.layer.cornerRadius = 5; [down addTarget:self action:@selector(down) forControlEvents:UIControlEventTouchUpInside]; cancel = [[UIButton alloc]initWithFrame:CGRectMake(120, 590, 40, 30)]; [cancel setTitle:@"取消" forState:UIControlStateNormal]; [cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; cancel.layer.borderWidth = 1; cancel.layer.borderColor = [UIColor blackColor].CGColor; cancel.layer.cornerRadius = 5; [cancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside]; stop = [[UIButton alloc]initWithFrame:CGRectMake(220, 590, 40, 30)]; [stop setTitle:@"掛起" forState:UIControlStateNormal]; [stop setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; stop.layer.borderWidth = 1; stop.layer.borderColor = [UIColor blackColor].CGColor; stop.layer.cornerRadius = 5; [stop addTarget:self action:@selector(stop) forControlEvents:UIControlEventTouchUpInside]; regain = [[UIButton alloc]initWithFrame:CGRectMake(320, 590, 40, 30)]; [regain setTitle:@"恢復" forState:UIControlStateNormal]; [regain setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; regain.layer.borderWidth = 1; regain.layer.borderColor = [UIColor blackColor].CGColor; regain.layer.cornerRadius = 5; [regain addTarget:self action:@selector(regain) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:textField]; [self.view addSubview:down]; [self.view addSubview:cancel]; [self.view addSubview:stop]; [self.view addSubview:regain]; [self.view addSubview:label]; [self.view addSubview:progress]; } -(void)down{ NSString *urlStr = textField.text; urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSURL *url = [NSURL URLWithString:urlStr]; //建立請求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //建立session會話 //配置session(默認會話--單例) NSURLSessionConfiguration *sessionConfig = [NSURLSessionConfiguration defaultSessionConfiguration]; //請求超時時間 sessionConfig.timeoutIntervalForRequest = 10; //是否容許蜂窩網絡下載(2G/3G/4G) sessionConfig.allowsCellularAccess = YES; //建立會話 NSURLSession *session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];//指定配置和代理 //代理 downLoad = [session downloadTaskWithRequest:request]; [downLoad resume]; } -(void)cancel{ [downLoad cancel]; } -(void)stop{ [downLoad suspend]; } -(void)regain{ [downLoad resume]; } //設置進度條狀態 -(void)setProgressStatus:(int64_t)totalBytesWritten expectedToWrite:(ino64_t)totalBytesExpectedToWrite{ //異步處理進度(獲取主隊列) dispatch_async(dispatch_get_main_queue(), ^{ progress.progress = (float)totalBytesWritten/totalBytesExpectedToWrite; if (totalBytesWritten == totalBytesExpectedToWrite) { 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{ NSLog(@"%lld %lld %lld",bytesWritten,totalBytesWritten,totalBytesExpectedToWrite); [self setProgressStatus:totalBytesWritten expectedToWrite:totalBytesExpectedToWrite]; } //下載完成 -(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ NSLog(@"%@",location); NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; path = [path stringByAppendingPathComponent:@"7170.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.localizedDescription); } } #pragma mark 任務完成時調用,不論是否成功 -(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ //若是有錯誤,打印一下 if (error) { NSLog(@"%@",error.localizedDescription); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end 簡化後的NSURLSession-------------------- #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [self downloadFile]; } -(void)downloadFile{ NSString *urlStr = @"http://b.zol-img.com.cn/desk/bizhi/image/6/2560x1600/1444631980385.jpg"; urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]]; NSURL *url = [NSURL URLWithString:urlStr]; //建立請求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; //建立會話(這裏使用一個全局會話) NSURLSession *session = [NSURLSession sharedSession]; //建立下載任務 NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { if (!error) { NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject]; path = [path stringByAppendingPathComponent:@"圖片7170.jpg"]; NSLog(@"%@",path); NSURL *saveUrl = [NSURL fileURLWithPath:path]; NSError *errorSave; [[NSFileManager defaultManager]copyItemAtURL:location toURL:saveUrl error:&errorSave]; if (!errorSave) { NSLog(@"保存成功"); }else{ NSLog(@"File Error is %@",errorSave.localizedDescription); } }else{ NSLog(@"下載出錯:%@",error.localizedDescription); } }]; [downloadTask resume]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end