网络-大文件下载(0621)
2015-06-21 21:38
519 查看
一、大文件下载 1.方案:利用NSURLConnection和它的代理方法 1> 发送一个请求 // 1.URL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/resources/videos.zip"]; // 2.请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 3.下载(创建完conn对象后,会自动发起一个异步请求) [NSURLConnection connectionWithRequest:request delegate:self]; 2> 在代理方法中处理服务器返回的数据 /** 在接收到服务器的响应时: 1.创建一个空的文件 2.用一个句柄对象关联这个空的文件,目的是:方便后面用句柄对象往文件后面写数据 */ - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // 文件路径 NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; NSString *filepath = [caches stringByAppendingPathComponent:@"videos.zip"]; // 创建一个空的文件 到 沙盒中 NSFileManager *mgr = [NSFileManager defaultManager]; [mgr createFileAtPath:filepath contents:nil attributes:nil]; // 创建一个用来写数据的文件句柄 self.writeHandle = [NSFileHandle fileHandleForWritingAtPath:filepath]; } /** 在接收到服务器返回的文件数据时,利用句柄对象往文件的最后面追加数据 */ - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { // 移动到文件的最后面 [self.writeHandle seekToEndOfFile]; // 将数据写入沙盒 [self.writeHandle writeData:data]; } /** 在所有数据接收完毕时,关闭句柄对象 */ - (void)connectionDidFinishLoading:(NSURLConnection *)connection { // 关闭文件 [self.writeHandle closeFile]; self.writeHandle = nil; } 2.注意点:千万不能用NSMutableData来拼接服务器返回的数据 二、NSURLConnection发送异步请求的方法 1.block形式 - 除开大文件下载以外的操作,都可以用这种形式 [NSURLConnection sendAsynchronousRequest:<#(NSURLRequest *)#> queue:<#(NSOperationQueue *)#> completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) { }]; 2.代理形式 - 一般用在大文件下载 // 1.URL NSURL *url = [NSURL URLWithString:@"http://localhost:8080/MJServer/login?username=123&pwd=123"]; // 2.请求 NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 3.下载(创建完conn对象后,会自动发起一个异步请求) [NSURLConnection connectionWithRequest:request delegate:self];
相关文章推荐
- nginx sendfile tcp_nopush tcp_nodelay参数解释
- gameUnity 0.15 beta 网络游戏框架
- Android模拟 HTTP multipart/form-data 请求协议信息实现图片上传
- POJ 3204 Ikki's Story I - Road Reconstruction 残余网络
- TCP三次握手和四次挥手协议
- 利用随机前馈神经网络生成图像观察网络复杂度
- TCP/IP协议族-----8、地址解析协议(ARP)
- 开源高性能网络库Libevent的简介
- http协议
- JAVA InputStream. 对网络数据帧自动分片
- 网络IO之阻塞、非阻塞、同步、异步总结【转】
- tcpdump导致无法上网
- Servlet介绍
- http-equiv
- IP地址子网掩码
- android开发网络请求的几种方法
- TCP/IP协议族-----7、网际协议版本4(IPv4)
- 基于VMware的网络配置
- http和socket通信的区别
- OSI七层模型与 TCP/IP五层模型 TCP/UDP的区别