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 ...
随机推荐
- ArcMap10.1无法保存编辑的内容
问题描述:在arcMap10.1中编辑SDE库中要素,保存编辑内容时报错: 无法保存编辑内容.基础DBMS错误[ORA-29877:failed in the execution of the ODC ...
- 12306验证图片的bug
刚才有人告诉我12306验证码换了,于是我就打开了看了看,点了点.oh no , i am really sorry ,12306.
- 王家林的81门一站式云计算分布式大数据&移动互联网解决方案课程第14门课程:Android软硬整合设计与框架揭秘: HAL&Framework &Native Service &App&HTML5架构设计与实战开发
掌握Android从底层开发到框架整合技术到上层App开发及HTML5的全部技术: 一次彻底的Android架构.思想和实战技术的洗礼: 彻底掌握Andorid HAL.Android Runtime ...
- 如何学习java ee
来看看Sun给出的J2EE 相关技术主要分为几大块. 1. Web Service技术 - Java API for XML Processing (JAXP) - Java API for XM ...
- WScript中调用js方法
http://zhidao.baidu.com/question/484374074.html ———————————————————————————————————————————————— Sub ...
- 13个Cat命令管理文件实例汇总
在Linux系统中,大多数配置文件.日志文件,甚至shell脚本都使用文本文件格式,因此,Linux系统存在着多种文本编辑器,但当你仅仅想要查看一下这些文件的内容时,可使用一个简单的命令-cat. c ...
- aspose.cell制作excel常见写法
//设置Excel的基本格式信息 Workbook workbook = new Workbook(); Worksheet worksheet = workbook.Worksheets[]; St ...
- 计算两个日期相隔的天数(jodd)
public static void main(String[] args) throws ParseException { System.out.println(TimeUtil.dayOfYear ...
- Check Box 用法
void CMyDlg::OnInitDialog() //Check1 初始化为选中状态 void CMyDlg::OnInitDialog() { CDialog::OnInitDialog(); ...
- SQLite本地事务处理
private void toolStripButton1_Click(object sender, EventArgs e) { //判断新增的年度是否已经存在 if (HasYear()) { M ...