文件下载(NSURLConnection/NSURLSession)
最基本的网络文件下载(使用原生的网络请求)
#pragma mark - 小文件下载
// 方法一: NSData dataWithContentsOfURL
- (void)downloadFile1
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, ), ^{
// 其实这就是一个GET请求
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/images/minion_01.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"%lu", data.length);
});
}
// 方法二: NSURLConnection
- (void)downloadFile2
{
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/images/minion_01.png"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%lu", data.length);
}];
}
//方法三:NSURLSession iOS7开始出现的 为取代NSURLConnection
- (void)downloadFile3
{
// 1.得到session对象
NSURLSession *session = [NSURLSession sharedSession]; // 2.创建一个下载task
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/test.mp4"];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL *location, NSURLResponse *response, NSError *error) {// location : 临时文件的路径(下载好的文件) NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// response.suggestedFilename : 建议使用的文件名,一般跟服务器端的文件名一致
NSString *file = [caches stringByAppendingPathComponent:response.suggestedFilename]; // 将临时文件剪切或者复制Caches文件夹
NSFileManager *mgr = [NSFileManager defaultManager]; // AtPath : 剪切前的文件路径
// ToPath : 剪切后的文件路径
[mgr moveItemAtPath:location.path toPath:file error:nil];
}]; // 3.开始任务
[task resume];
}
#pragma mark - 大文件下载
//方法一: NSURLConnection (合理:单个线程 下载一点就写入一点)使用NSFileHandle
//句柄对象
@property (nonatomic, strong) NSFileHandle * writeHandle; - (void)downloadFile4
{
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 下载(创建完conn对象后,会自动发起一个异步请求,通过delegate回调下载信息)
[NSURLConnection connectionWithRequest:request delegate:self];
} #pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{//请求失败 } // 1.接收到服务器的响应就会调用
- (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];
} // 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 移动到文件的最后面
[self.writeHandle seekToEndOfFile]; // 将数据写入沙盒
[self.writeHandle writeData:data];
} // 3.加载完毕后调用(服务器的数据已经接收完毕)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
// 关闭文件 设置为空
[self.writeHandle closeFile];
self.writeHandle = nil;
}
//方法二: NSURLConnection 使用NSOutputStream //文件流
@property (nonatomic, strong) NSOutputStream * fileStream; - (void)downloadFile6
{
NSURL *url = [NSURL URLWithString:@"http://localhost:8080/Server/resources/videos.zip"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; // 下载(创建完conn对象后,会自动发起一个异步请求,通过delegate回调下载信息)
[NSURLConnection connectionWithRequest:request delegate:self];
} #pragma mark - NSURLConnectionDataDelegate
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{//请求失败 } // 1.接收到服务器的响应就会调用
- (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.fileStream = [NSOutputStream outputStreamToFileAtPath:filepath append:YES];
} // 2.当接收到服务器返回的实体数据时调用(具体内容,这个方法可能会被调用多次)
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//将数据追加到文件流中
[self.fileStream write:data.bytes maxLength:data.length];
} // 3.加载完毕后调用(服务器的数据已经接收完毕)
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
{
// 关闭文件流
[self.fileStream close];
}
更多内容--> 博客导航 每周一篇哟!!!
有任何关于iOS开发的问题!欢迎下方留言!!!或者邮件lieryangios@126.com 虽然我不一定能够解答出来,但是我会请教iOS开发高手!!!解答您的问题!!!
文件下载(NSURLConnection/NSURLSession)的更多相关文章
- NSURLConnection / NSURLSession/ SDWebImage
1. NSURLConnection (iOS9开始被弃用)=========================================== 此类的对象加载一个URL请求对象,通过异步/同步的方 ...
- iOS NSURLSession VS NSURLConnection
NSURLSession VS NSURLConnection NSURLSession可以看做是NSURLConnection的进化版,其对NSURLConnection的改进点有: * 根据每个S ...
- iOS网络-04-大文件下载
大文件下载注意事项 若不对下载的文件进行转存,会造成内存消耗急剧升高,甚至耗尽内存资源,造成程序终止. 在文件下载过程中通常会出现中途停止的状况,若不做处理,就要重新开始下载,浪费流量. 大文件下载的 ...
- OC - 16.大文件下载
大文件下载注意事项 若不对下载的文件进行转存,会造成内存消耗急剧升高,甚至耗尽内存资源,造成程序终止. 在文件下载过程中通常会出现中途停止的状况,若不做处理,就要重新开始下载,浪费流量. 大文件下载的 ...
- iOS开发系列-文件下载
小文件下载 NSURLConnection下载小文件 #import "ViewController.h" @interface ViewController ()<NSUR ...
- NSURLSession 相关清单
浅析 NSURLSession http://boboshone.com/blog/2013/10/21/nsurlsession-tutorial/ 介绍整体流程结构. iOS NSURL ...
- 实战iOS7之NSURLSession
NSURLSession VS NSURLConnection NSURLSession可以看做是NSURLConnection的进化版,其对NSURLConnection的改进点有: * 根据每个S ...
- iOS-技巧性总结
1.AFN与ASI对比 -- AFN1. 基于 NSURLConnection & NSURLSession 进行的封装2. 使用简单3. 提供了自动的序列化 & 反序列化支持! AF ...
- [ 流行的网络框架 ] AFN & ASI
1.AFN & ASI(早已经停止更新,但现在许多公司也在使用.) AFNetWorking地址:https://github.com/AFNetworking/AFNetworking AS ...
随机推荐
- 关于c语言中的字符串问题
对字符数组,字符指针,字符串常量 在csdn上看到一篇关于这方面的帖子,有所收获. JohnTitor的专栏 1.以字符串形式出现的,编译器都会为该字符串自动添加一个0作为结束符,如在代码中写 & ...
- Python学习笔记(socket)
socket(数据传输接口) 搭建服务端 1.导入模块 import socket 2.创建socket对象 sock=socket .socket(socket_family,socket_topy ...
- 乐字节-Java8核心特性实战之Stream(流)
说起流,我们会想起手机 ,电脑组装流水线,物流仓库商品包装流水线等等.如果把手机 ,电脑,包裹看做最终结果的话,那么加工商品前的各种零部件就可以看做数据源,而中间一系列的加工作业操作,就可以看做流的处 ...
- P1308-道路修建 (noi 2011)
题目描述 在 W 星球上有 n 个国家.为了各自国家的经济发展,他们决定在各个国家 之间建设双向道路使得国家之间连通.但是每个国家的国王都很吝啬,他们只愿 意修建恰好 n – 1 条双向道路. 每条道 ...
- 有关xerosploit运行报错问题的有效解决方案
[安装xerosploit]安装xerosploit的步骤如下,我是将xerosploit直接克隆到了根目录下(使用“cd /”到达根目录) git clone https://github.com/ ...
- HDU-1845-Jimmy's Assignment
链接:https://vjudge.net/problem/HDU-1845 题意: 给一个有向图,求最大匹配. 思路: 有相图的最大匹配,可以通过加上反向边, 求这个无向图的最大匹配, 原图的最大匹 ...
- loj#6169. 相似序列 hash+主席树
因为他的相似是在排完序下的 那我就在排序的情况下hash啊 这怎么hash啊 主席树啊! 没了 #include <bits/stdc++.h> #define MAXNODE 50000 ...
- Net Core -- 配置Kestrel端口
Net Core -- 配置Kestrel端口 Kestrel介绍 在Asp.Net Core中,我们的web application 其实是运行在Kestrel服务上,它是一个基于libuv开源的跨 ...
- MySQL 实现字符串换行
target_describe字段值中包含 :[ 这两个特殊的字符 ,想要在字符之间加换行 需要插入CHAR(10) ),'[')) UPDATE ew_pm_project_red_detail S ...
- tomcat调优方案Maximum number of threads (200) created for connector with address null and port 8091
1.tomcat6大并发出现:INFO: Maximum number of threads (200) created for connector with address null and por ...