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 ...
随机推荐
- iOS事件机制(一)
运用的前提是掌握 掌握的本质是理解 本篇内容将围绕iOS中事件及其传递机制进行学习和分析.在iOS中,事件分为三类: 触控事件(单点.多点触控以及各种手势操作) 传感器事件(重力.加速度传感器等) 远 ...
- SaltStack安装Redis模块
安装redis Python Client 下载地址: https://pypi.python.org/simple/redis/ tar -xvf redis-2.8.0.tar.gz cd red ...
- [iOS基础控件 - 6.10.2] PickerView 自定义row内容 国家选择Demo
A.需求 1.自定义一个UIView和xib,包含国家名和国旗显示 2.学习row的重用 B.实现步骤 1.准备plist文件和国旗图片 2.创建模型 // // Flag.h // Co ...
- HDU 4460 Friend Chains (BFS,最长路径)
题意:给定 n 个人,和关系,问你这个朋友圈里任意两者之间最短的距离是多少. 析:很明显的一个BFS,只要去找最长距离就好.如果不能全找到,就是-1. 代码如下: #pragma comment(li ...
- ADO.NET 快速入门(七):使用数据库事务
数据库事务用于控制数据提交到数据库.例如,在标准的账户程序,账户的借贷必须同时完成.由于电脑偶尔发生故障(电力中断.网络中断,等等),可能有些记录被更新或者添加,但是另外一些没有.为了避免这些情况,可 ...
- 教你50招提升ASP.NET性能(十四):使用startMode属性来减少ASP.NET站点加载时间
(25)Use the startMode attribute to reduce the load time for your ASP.NET site 招数25: 使用startMode属性来减少 ...
- 使用VS2012 开发SharePoint 2013 声明式的action(activity) 综合实例
本文讲述使用VS2012 开发SharePoint 2013 声明式的action 综合实例. 需求同: http://blog.csdn.net/abrahamcheng/article/detai ...
- zoj 3511 Cake Robbery(线段树)
problemCode=3511" target="_blank" style="">题目链接:zoj 3511 Cake Robbery 题目 ...
- 第十七章,txt文件的写入和读取数据结合练习(C++)
#include <iostream> #include <fstream> int main(int argc, char** argv) { std::string str ...
- 关于AS3的垃圾回收
FlashPlayer运行GC(Gabage Collection)的时间并不固定,它会根据你的内存的占用情况来决定运行GC的时间.它会根据用户机器的内存值来设定一个阀值,然后将程序的占用内存量保存在 ...