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 ...
随机推荐
- Web Service学习之一:Web Service原理
一.定义 Web Service 不是框架也不是技术 而是解决远程调用.跨平台调用.跨语言调用问题的一种规范. 二.应用1.同一个公司新.旧系统的整合:比如CRM系统与OA.客服系统相互调用2.不同公 ...
- HDU 5816 Hearthstone (状压DP)
Hearthstone 题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5816 Description Hearthstone is an onlin ...
- SpringDataMongoDB介绍(二)-MongoOperations介绍
MongoOperations是一个很强大的接口,有了这个接口,基本上什么都搞定了. 其介绍 Interface that specifies a basic set of MongoDB opera ...
- Spring入门(8)-基于Java配置而不是XML
Spring入门(8)-基于Java配置而不是XML 本文介绍如何应用Java配置而不是通过XML配置Spring. 0. 目录 声明一个简单Bean 声明一个复杂Bean 1. 声明一个简单Bean ...
- linux下安装apache详解
下载httpd-2.2.6.tar.bz2 把httpd-2.2.6.tar.bz2放到/soft 下[root@localhost ~]#cd /soft[root@localhost soft] ...
- AVCaptureDevice的几个属性
AVCaptureDevice.h,主要用来获取iphone一些关于相机设备的属性. AVCaptureDevice.h,必须要引入AVFoundation.framework包. 1. 前置和后置摄 ...
- ADO.NET 快速入门(十三):使用 OLE DB 检索数据
OleDbDataReader 类提供了一种从数据源读取数据记录只进流的方法.如果想使用 SQL Server 7.0 或者更高版本,请参考文章:使用 SQL Server 检索数据. OleDb ...
- SQL性能优化工具TKPROF
全名为Trace Kernel Profile,用来格式化跟踪文件,是一个命令行工具. 主要的格式例如以下: tkprof tracefile outputfile - tracefile:要分 ...
- HDU 5570 balls 期望 数学
balls Time Limit: 20 Sec Memory Limit: 256 MB 题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=5570 De ...
- AES加密算法(C++实现,附源代码)
先搞定AES算法,基本变换包含SubBytes(字节替代).ShiftRows(行移位).MixColumns(列混淆).AddRoundKey(轮密钥加) 其算法一般描写叙述为 明文及密钥的组织排列 ...