网络通信中关于请求数据、断点续传和写入本地文件
2015-09-10 09:39
507 查看
- (void)viewDidLoad { [super viewDidLoad]; NSLog(@"%@",NSHomeDirectory()); //取得已下载数据大小 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; receiveTotal = [[userDefaults objectForKey:@"ReceiveTotal"] doubleValue]; total = [[userDefaults objectForKey:@"Total"] doubleValue]; //显示上一次下载的进度 if (total > 0) { CGFloat progress = receiveTotal/total; self.progressView.progress = progress; self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%", progress * 100]; }
}- (IBAction)downLoadClick:(UIButton *)sender { if (!isDownLoad) { //1.构建URL NSURL *url = [NSURL URLWithString:@"http://s.qdcdn.com/lovebizhi/LoveWallpaper4Mac.dmg"]; //2.构建Request NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url]; //断点续传 if (receiveTotal > 0) { //设置续传位置 NSString *position = [NSString stringWithFormat:@"bytes=%d-",(int)receiveTotal]; [mRequest setValue:position forHTTPHeaderField:@"Range"]; } //3.发送异步请求 connection = [NSURLConnection connectionWithRequest:mRequest delegate:self]; isDownLoad = YES; //获取字符串 NSString *urlStr = url.absoluteString; //获取urlStr的最后一部分 NSString *fileName = [urlStr lastPathComponent]; //写入文件 filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",fileName];
//创建文件 [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; }}
//暂停下载- (IBAction)pauseClick:(UIButton *)sender { //取消下载连接 [connection cancel]; connection = nil; //将缓冲数据写入文件 [self appendFileData:self.receiveData]; //在本地保存已下载文件的大小和文件总大小 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:@(receiveTotal) forKey:@"ReceiveTotal"]; [userDefaults setObject:@(total) forKey:@"Total"]; //将数据同步写入文件 [userDefaults synchronize]; isDownLoad = NO;}
#pragma mark-NSURLConnectionDataDelegate//服务器响应- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{ self.receiveData = [[NSMutableData alloc]init]; //判断总大小是否为0,如果为0,说明从起始位置开始下,获取文件总大小 if (total == 0) { //获取所有的响应头 NSDictionary *fields = response.allHeaderFields; NSLog(@"fields is %@",fields); //获取数据的总大小 NSNumber *length = [fields objectForKey:@"Content-Length"]; total = [length doubleValue]; NSLog(@"total is %.2f",total);
} }
//接收数据- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [self.receiveData appendData:data]; receiveTotal += data.length; //计算进度 double progress = receiveTotal / total; //刷新UI self.progressView.progress = progress; self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%",progress * 100]; //判断缓冲的数据是否大于500KB if (self.receiveData.length >= 500 * 1024) { //写入数据 [self appendFileData:self.receiveData]; //清空 self.receiveData.data = nil; }}
//数据传输完成- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//将最后一个缓冲文件写入 if (self.receiveData.length < 500 * 1024) { //写入数据 [self appendFileData:self.receiveData]; //清空 self.receiveData.data = nil;
} _progressLabel.text = @"下载完成"; self.progressView.progress = 0;
isDownLoad = NO;}
- (void)appendFileData:(NSData *)data{ if (data.length == 0) { return; } //使用NSFileHandle写文件,此文件必须已经创建,NSFileHandle不会创建文件 NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; //将数据插入到写入点 [fileHandle seekToEndOfFile]; [fileHandle writeData:data]; //关闭文件,确保写入完成 [fileHandle closeFile]; }- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}
}- (IBAction)downLoadClick:(UIButton *)sender { if (!isDownLoad) { //1.构建URL NSURL *url = [NSURL URLWithString:@"http://s.qdcdn.com/lovebizhi/LoveWallpaper4Mac.dmg"]; //2.构建Request NSMutableURLRequest *mRequest = [NSMutableURLRequest requestWithURL:url]; //断点续传 if (receiveTotal > 0) { //设置续传位置 NSString *position = [NSString stringWithFormat:@"bytes=%d-",(int)receiveTotal]; [mRequest setValue:position forHTTPHeaderField:@"Range"]; } //3.发送异步请求 connection = [NSURLConnection connectionWithRequest:mRequest delegate:self]; isDownLoad = YES; //获取字符串 NSString *urlStr = url.absoluteString; //获取urlStr的最后一部分 NSString *fileName = [urlStr lastPathComponent]; //写入文件 filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",fileName];
//创建文件 [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil]; }}
//暂停下载- (IBAction)pauseClick:(UIButton *)sender { //取消下载连接 [connection cancel]; connection = nil; //将缓冲数据写入文件 [self appendFileData:self.receiveData]; //在本地保存已下载文件的大小和文件总大小 NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; [userDefaults setObject:@(receiveTotal) forKey:@"ReceiveTotal"]; [userDefaults setObject:@(total) forKey:@"Total"]; //将数据同步写入文件 [userDefaults synchronize]; isDownLoad = NO;}
#pragma mark-NSURLConnectionDataDelegate//服务器响应- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response{ self.receiveData = [[NSMutableData alloc]init]; //判断总大小是否为0,如果为0,说明从起始位置开始下,获取文件总大小 if (total == 0) { //获取所有的响应头 NSDictionary *fields = response.allHeaderFields; NSLog(@"fields is %@",fields); //获取数据的总大小 NSNumber *length = [fields objectForKey:@"Content-Length"]; total = [length doubleValue]; NSLog(@"total is %.2f",total);
} }
//接收数据- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [self.receiveData appendData:data]; receiveTotal += data.length; //计算进度 double progress = receiveTotal / total; //刷新UI self.progressView.progress = progress; self.progressLabel.text = [NSString stringWithFormat:@"%.2f%%",progress * 100]; //判断缓冲的数据是否大于500KB if (self.receiveData.length >= 500 * 1024) { //写入数据 [self appendFileData:self.receiveData]; //清空 self.receiveData.data = nil; }}
//数据传输完成- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
//将最后一个缓冲文件写入 if (self.receiveData.length < 500 * 1024) { //写入数据 [self appendFileData:self.receiveData]; //清空 self.receiveData.data = nil;
} _progressLabel.text = @"下载完成"; self.progressView.progress = 0;
isDownLoad = NO;}
- (void)appendFileData:(NSData *)data{ if (data.length == 0) { return; } //使用NSFileHandle写文件,此文件必须已经创建,NSFileHandle不会创建文件 NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:filePath]; //将数据插入到写入点 [fileHandle seekToEndOfFile]; [fileHandle writeData:data]; //关闭文件,确保写入完成 [fileHandle closeFile]; }- (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated.}
相关文章推荐
- C#文件断点续传实现方法
- VB读取线程、句柄及写入内存的API代码实例
- C#通过流写入一行数据到文件的方法
- C#实现xml文件的读取与写入简单实例
- python支持断点续传的多线程下载示例
- 桌面中心(二)数据库写入
- PHP实现文件下载断点续传详解
- php写入、删除与复制文件的方法
- c#实现断点续传功能示例分享
- php实现的支持断点续传的文件下载类
- C#实现将日志写入文本文件的方法
- PHP实现HTTP断点续传的方法
- android 网络编程之网络通信几种方式实例分享
- Android实现将已发送的短信写入短信数据库的方法
- Python3写入文件常用方法实例分析
- go语言实现将重要数据写入图片中
- php笔记之:有规律大文件的读取与写入的分析
- PHP使用range协议实现输出文件断点续传代码实例
- 在ASP.NET中支持断点续传下载大文件(ZT)源码
- JavaScript中对象property的读取和写入方法介绍