赞
踩
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;
- }
- /* 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];
- });
-
-
-
- }

- /**
- [""] * @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];
-
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。