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 ...
随机推荐
- Spark系列(七)Master中的资源调度
资源调度 说明: Application的调度算法有两种,分别为spreadOutApps和非spreadOutApps spreadOutApps 在spark-submit脚本中,可以指定要多少个 ...
- Unity3D文件读写
这里主要是简单的文件读写,不推荐使用,最好用的还是PlayerPrefs. using UnityEngine; using System.Collections; using System.IO; ...
- POj3268 Silver Cow Party
http://poj.org/problem?id=3268 题目大意:求到x距离与从x返回和的最大值 从x点到各个点最短路好求,直接用Dijkstar,但从各个点到x点却不好求,只要把路向翻转过来也 ...
- Codeforces 626A Robot Sequence
A. Robot Sequence time limit per test 2 seconds memory limit per test 256 megabytes input standard i ...
- BestCoder Round #71 (div.2) (hdu 5620 菲波那切数列变形)
KK's Steel Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total ...
- [C语言 - 7] 结构体struct
A. 基本知识 与数组的对比 数组: 构造类型 只能有多个相同类型的数据构成 结构体: 结构体类型 可以由多个不同类型的数据构成 1. 定义类型 struct Student { int ...
- Java虚拟机学习 - 体系结构 内存模型
一:Java技术体系模块图 二:JVM内存区域模型 1.方法区 也称"永久代” .“非堆”, 它用于存储虚拟机加载的类信息.常量.静态变量.是各个线程共享的内存区域.默认最小值为16MB,最 ...
- CABasicAnimation精讲
前言 本教程写了这个效果图的demo,同时总结CABasicAnimation的使用方法. 看完gif动画完,看到了什么?平移.旋转.缩放.闪烁.路径动画. 实现平移动画 实现平移动画,我们可以通过t ...
- 关于mysql_fetch_****
今天调试如下代码: mysql_select_db('content',$link);//选择数据库 mysql_query("set names utf8");//设置编码格式 ...
- Grand Central Dispatch(GCD)编程基础
GCD:线程 http://blog.csdn.net/nono_love_lilith/article/details/7829557