1.创建request
- (void)download2 { NSString *urlString = @"http:192.168.0.179:8080/Myweb/download.do"; urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"hello"); NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; [[self.session downloadTaskWithRequest:request] resume]; }
最后一句
[[self.session downloadTaskWithRequest:request] resume];
的session,本文使用懒加载
2. session懒加载,并添加代理,监听文件下载情况
// 懒加载 - (NSURLSession *)session { if(_session == nil) { NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; _session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; } return _session; }
3.进度更新和label下载完成百分比更新(注意,一定要在主线程更新,不然无法显示)
/* Sent periodically to notify the delegate of download progress. */ /** [""] * @brief 更新进度条,使用此代理 [""] * [""] * @param session session [""] * @param downloadTask 下载任务 [""] * @param bytesWritten 当前写入bytes [""] * @param totalBytesWritten 当前总共写入bytes [""] * @param totalBytesExpectedToWrite 期望写入的总bytes [""] * [""] * @return <#return value description#> [""] */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { float progress = (float)totalBytesWritten / totalBytesExpectedToWrite; NSLog(@"%f", progress); //主线程更新UI dispatch_async(dispatch_get_main_queue(), ^(void){ self.progressLabel.text=[NSString stringWithFormat:@"%%%.0f",progress*100]; [self.progressView setProgress:progress animated:YES]; }); }
4. 下载完成,将下载的数据写入指定缓存路径。
/** [""] * @brief The delegate should copy or move the file at the given location to a new location as it will be removed when the delegate message returns. [""] * [""] * @param session session description [""] * @param downloadTask downloadTask 下载任务 [""] * @param location 下载文档位置(临时) [""] * [""] * @return [""] */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location { NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0]; NSString *retStr = [downloadTask.response.suggestedFilename stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSLog(@"%@ \n",retStr); NSString *path = [cacheDir stringByAppendingPathComponent:retStr]; NSLog(@"%@",path); //NSURL *url2=location; NSLog(@"%@",location); NSData *mydata=[NSData dataWithContentsOfURL:location]; [mydata writeToFile:path atomically:YES]; }
时间: 2024-10-28 01:04:26