iOS 文件下载
来源:互联网 发布:淘宝提交营业执照 编辑:程序博客网 时间:2024/05/01 02:26
1、小文件下载
@interface ViewController () <NSURLConnectionDataDelegate>@property (weak, nonatomic) IBOutlet UIProgressView *progressView;/** 文件数据 */@property (nonatomic, strong) NSMutableData *fileData;/** 文件的总长度 */@property (nonatomic, assign) NSInteger contentLength;@end
- (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"]; [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];}#pragma mark - <NSURLConnectionDataDelegate>- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{ self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue]; self.fileData = [NSMutableData data];}- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [self.fileData appendData:data]; CGFloat progress = 1.0 * self.fileData.length / self.contentLength; NSLog(@"已下载:%.2f%%", (progress) * 100); self.progressView.progress = progress;}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ NSLog(@"下载完毕"); // 将文件写入沙盒中 // 缓存文件夹 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; // 文件路径 NSString *file = [caches stringByAppendingPathComponent:@"minion_15.mp4"]; // 写入数据 [self.fileData writeToFile:file atomically:YES]; self.fileData = nil;}
2、大文件下载
#define XMGFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"minion_15.mp4"]@interface ViewController () <NSURLConnectionDataDelegate>@property (weak, nonatomic) IBOutlet UIProgressView *progressView;/** 文件的总长度 */@property (nonatomic, assign) NSInteger contentLength;/** 当前下载的总长度 */@property (nonatomic, assign) NSInteger currentLength;/** 文件句柄对象 */@property (nonatomic, strong) NSFileHandle *handle;@end
- (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"]; [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];}
#pragma mark - <NSURLConnectionDataDelegate>/** * 接收到响应的时候:创建一个空的文件 */- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{ // 获得文件的总长度 self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue]; // 创建一个空的文件 [[NSFileManager defaultManager] createFileAtPath:XMGFile contents:nil attributes:nil]; // 创建文件句柄 self.handle = [NSFileHandle fileHandleForWritingAtPath:XMGFile];}/** * 接收到具体数据:马上把数据写入一开始创建好的文件 */- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ // 指定数据的写入位置 -- 文件内容的最后面 [self.handle seekToEndOfFile]; // 写入数据 [self.handle writeData:data]; // 拼接总长度 self.currentLength += data.length; // 进度 self.progressView.progress = 1.0 * self.currentLength / self.contentLength;}- (void)connectionDidFinishLoading:(NSURLConnection *)connection{ // 关闭handle [self.handle closeFile]; self.handle = nil; // 清空长度 self.currentLength = 0;}
大文件断点下载
// resumeData的文件路径#define XMGResumeDataFile [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"resumeData.tmp"]#import "ViewController.h"@interface ViewController () <NSURLSessionDownloadDelegate>/** 下载任务 */@property (nonatomic, strong) NSURLSessionDownloadTask *task;/** 保存上次的下载信息 */@property (nonatomic, strong) NSData *resumeData;/** session */@property (nonatomic, strong) NSURLSession *session;@end
@implementation ViewController/** session */- (NSURLSession *)session{ if (!_session) { _session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; } return _session;}/** * 开始下载 */- (IBAction)start:(id)sender { self.task = [self.session downloadTaskWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"]]; [self.task resume];}/** * 暂停下载 */- (IBAction)pause:(id)sender { // 一旦这个task被取消了,就无法再恢复 [self.task cancelByProducingResumeData:^(NSData *resumeData) { self.resumeData = resumeData; }];}/** * 继续下载 */- (IBAction)goOn:(id)sender { self.task = [self.session downloadTaskWithResumeData:self.resumeData]; [self.task resume];}#pragma mark - <NSURLSessionDownloadDelegate>- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{ NSLog(@"didCompleteWithError"); // 保存恢复数据 self.resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];}- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes{ NSLog(@"didResumeAtOffset");}/** * 每当写入数据到临时文件时,就会调用一次这个方法 * totalBytesExpectedToWrite:总大小 * totalBytesWritten: 已经写入的大小 * bytesWritten: 这次写入多少 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{ NSLog(@"--------%f", 1.0 * totalBytesWritten / totalBytesExpectedToWrite);}/** * * 下载完毕就会调用一次这个方法 */- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{ // 文件将来存放的真实路径 NSString *file = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; // 剪切location的临时文件到真实路径 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:file] error:nil];}@end
0 0
- ios下载文件
- IOS文件下载
- IOS文件下载
- IOS下载文件
- iOS文件下载
- 【iOS】文件下载小记
- 文件下载 ios
- iOS 文件分段下载
- iOS AFNetworking下载文件
- iOS 文件下载断点续传
- iOS网络文件下载
- ios 大文件下载
- iOS 文件下载
- iOS文件下载
- iOS 文件下载
- iOS文件分段下载
- iOS 文件下载
- iOS 文件下载
- java单元测试入门——JUnit
- OpenSSH服务安全20招
- 工作中遇到的将json重新构建的例子
- Retrofit网络通信库简单封装使用
- google.maps.Map 的事件
- iOS 文件下载
- 使用Linux raw socket时需要注意的一些问题
- cscf
- Appium 安装时遇到的各种奇葩问题
- Android自动填写获取到的验证码
- spring2.5注解驱动(一)
- 一只测试喵的重新启航
- DatePicker遇到的一些问题
- java数据转换