NSURLConnection、NSURLSession
//用于存储网络下载的数据.把分包的数据整合起来.
@property (nonatomic, strong) NSMutableData *receivedData;
// NSURL OC的URL类型,地址资源定位
NSURL *url = [NSURL URLWithString:@"http://www.tmooc.cn"];
// OC的请求类型,包含了请求相关的操作.例如缓存.cookie等等...
// startImmediately 立刻开始
// YES代表立刻开始请求,
// NO 不需要立刻开始,需要手动触发.
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
// 手动开始请求
[conn start];
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"didReceiveResponse:%@", response);
_receivedData = [[NSMutableData alloc] init];
// 由于data有可能是分批的,所以我们需要一个全局的MutableData去拼接起来
NSLog(@"didReceiveData:%ld个字节", data.length);
[_receivedData appendData:data];
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSString *path = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/baidu"];
// 使用NSUTF8StringEncoding编码类型,对_receivedData这个二进制类型进行转码,转换为字符串
NSString *baiduStr = [[NSString alloc] initWithData:_receivedData encoding:NSUTF8StringEncoding];
// 定义一个error指针,不需要初始化
// error指针的初始化由下面的方法来完成. 如果有错误就会被赋值. 没错误,依然会是nil
NSError *error = nil;
[baiduStr writeToFile:path atomically:NO encoding:NSUTF8StringEncoding error:&error];
if (error) {
// error有值,则说明上面的写文件方法出错了
NSLog(@"error:%@", error);
}
//好处:便于维护. 特别是一个常量 要很多个位置使用时
//习惯上,添加k为前缀
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSLog(@"接收到%ld字节的数据", data.length);
}];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// 用于存储服务器返回的响应,参考delegate方式中的didReceiveResponse
NSURLResponse *response = nil;
NSError *error = nil;
// 发送同步请求
NSTimeInterval beginTime =[NSDate timeIntervalSinceReferenceDate];
NSData *receivedData =[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(@"接收到%ld个字节的数据", receivedData.length);
NSTimeInterval endTime = [NSDate timeIntervalSinceReferenceDate];
客户端: 主动的角色
客户端必须告诉服务器当前应该从哪个地方开始继续下载
如何告诉, 通过http协议的数据包?
客户端 —http> 服务器
key(BigFile.zip: 600M):
//断点传输
@property(nonatomic,strong)NSMutableURLRequest *request;//要使用可变的请求对象
@property(nonatomic,strong)NSURLConnection *conn;
- (void)viewDidLoad {
[super viewDidLoad];
self.cachePath=[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
- (IBAction)downloadBigFile:(UIButton *)sender {
NSURL *url=[NSURL URLWithString:@"http://localhost:80/Evernote.zip"];
//设置range:bytes=0-
}
- (IBAction)cancelDownLoad:(UIButton *)sender {
//取消下载
[self.conn cancel];
self.conn=nil;
}
- (IBAction)resumeDownLoad:(UIButton *)sender {
//恢复下载
//Range:bytes=
NSString *range=[NSString stringWithFormat:@"bytes=%lld-",self.currentLength];
//客户端请求成功,接收到响应response
NSLog(@"status:%ld",(long)status);
NSString *fliePath=[self.cachePath stringByAppendingPathComponent:@"text.zip"];
//获取文件的总大小(为了显示进度)
//接收到数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
//当前接收数据包的大小
static int i=0;
i++;
NSLog(@"当前接收数据大小_%d:%ld",i,(unsigned long)data.length);
//移动到文件尾部
self.currentLength +=data.length;
NSLog(@"总接收数据:%lld",self.currentLength);
self.progressView.progress = (double)self.currentLength / self.totalLength;
//下载完成后,关闭句柄
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
[self.writeHandle closeFile];
}
//错误处理
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
2.通过URL将数据下载到文件系统
3.将数据上传到指定的URL
1、NSURLSessionDataTask:
NSURLSession *session=[NSURLSession sharedSession];//使用默认的session(回话)方式
NSInteger status=[(NSHTTPURLResponse *)response statusCode];//服务器返回的编号
NSLog(@"status:%ld",(long)status);
if (status ==200) {
NSLog(@"location:%@",location);
NSLog(@"response : %@",response);
NSString *path=[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:@"mm.jpg"];
NSLog(@"path :%@",path);
//2、移动文件
[[NSFileManager defaultManager]moveItemAtPath:location.path toPath:path error:nil];
//显示图片
self.imageView.image=image;
});
}
}];
//执行下载任务
[downloadTask resume];
NSURLConnection、NSURLSession的更多相关文章
- NSURLConnection、NSURLSession 补充
一.大文件下载1.方案:利用NSURLConnection和它的代理方法1> 发送一个请求 // 1.URL NSURL *url = [NSURL URLWithString:@"h ...
- iOS开发之网络编程--1、NSURLSession的基本使用
前言:学习NSURLSession的使用之前,先学习一篇关于NSURLSession的好文章<From NSURLConnection to NSURLSession>或者是国内的译文&l ...
- iOS网络学习之“远离NSURLConnection 走进NSURLSession”
目前,在iOS的开发中,NURLConnection已经成为了过去式,现在的NSURLConnection已经deprected(iOS7之后),取而代之的是NSURLSession.而且AFNetw ...
- 从 NSURLConnection 到 NSURLSession
iOS 7 和 Mac OS X 10.9 Mavericks 中一个显著的变化就是对 Foundation URL 加载系统的彻底重构. 现在已经有人在深入苹果的网络层基础架构的地方做研究了,所以我 ...
- 简单使用NSURLConnection、NSURLRequest和NSURL
以下是代码,凝视也写得比較清楚: 头文件须要实现协议NSURLConnectionDelegate和NSURLConnectionDataDelegate // // HttpDemo.h // My ...
- 使用NSURLProtocol和NSURLSession拦截UIWebView的HTTP请求(包括ajax请求)
问题:服务器端有一个网站需要AD认证,整站都开了Basic认证,包括图片,CSS等资源,我在HTTP请求头里面添加认证所需的用户名和密码,传递到服务器端可以认证通过.我在UIWebView的shoul ...
- 【原】HTTP in iOS你看我就够
声明:本文是本人 编程小翁 原创,转载请注明. 本文同步发布在简书中,强烈建议移步简书查看,编程小翁 HTTP属于老话题了,在项目中我们经常需要往服务端发POST或者GET请求,但是对于HTTP的了解 ...
- iOS网络相关知识总结
iOS网络相关知识总结 1.关于请求NSURLRequest? 我们经常讲的GET/POST/PUT等请求是指我们要向服务器发出的NSMutableURLRequest的类型; 我们可以设置Reque ...
- HTTP in iOS你看我就够
HTTP属于老话题了,在项目中我们经常需要往服务端发POST或者GET请求,但是对于HTTP的了解不应只局限于此.千里之行,始于足下.越想走的远,基本原理就应该了解的透彻全面一些,仅仅停留在使用ASI ...
随机推荐
- 窥探JVM内存分配和回收的过程
一.环境 JDK 垃圾收集器 是否启用TLAB 通用JVM参数(堆内存分配见下图) 1.6.0_65 Serial + Serial Old 否 -Xms20m -Xmx20m -Xmn10m -XX ...
- Java设计模式系列之桥接模式
桥接模式(Bridge)的定义 在软件系统中,某些类型由于自身的逻辑,它具有两个或多个维度的变化,那么如何应对这种“多维度的变化”?这就要使用桥接模式 将抽象部分与它的实现部分分离,使它们都可以独立地 ...
- Test Spring el with ExpressionParser
Spring expression language (SpEL) supports many functionality, and you can test those expression fea ...
- [iOS微博项目 - 1.4] - 各种item NavigationBar & NavigationItem & BarButtonItem || TabBar & TabBarItem
一.UINavigationItem1> 获得方式self.navigationItem // self是指控制器2> 作用可以用来设置当前控制器顶部导航栏的内容// 设置导航栏中间的内容 ...
- 用ALAssetsLibrary将过滤后图片写入照片库
转载自:http://blog.sina.com.cn/s/blog_61235faa0100z3dp.html CIImage *saveToSave = [filter outputImage]; ...
- AVCaptureSession 照相时获取 AVCaptureVideoPreviewLayer尺寸
http://stackoverflow.com/questions/14153878/avcapturesession-preset-photo-and-avcapturevideopreviewl ...
- Educational Codeforces Round 7 - E. Ants in Leaves
题目链接:http://www.codeforces.com/contest/622/problem/E 题意是给你一棵树,1为根,每个叶子节点有一个蚂蚁,移动到一个邻接节点时间耗费为1,一个节点上不 ...
- Map 排序
/** * 通过map 的 value 排序,并返回排序后的第一个条目 * * @param m 待排序集合 * @param desc true:降序排序,false:升序排序 * @return ...
- RIA(富客户端)发展态势
在过去的两到三年中,Web开发人员一直是想构建一种比传统HTML更丰富的客户端:这是一个用户接口,它比用HTML能实现的接口更加健壮.反应更加灵敏和更具有令人感兴趣的可视化特性.RIA技术的出现允许我 ...
- python的locals()妙用
如果你是个喜欢偷懒的程序员并想让代码看起来更加简明,可以利用 Python 的内建函数 locals() .它返回的字典对所有局部变量的名称与值进行映射.因此,前面的视图可以重写成下面这个样子:def ...