网络热恋之NSURLSession
//
// ViewController.m
// NSURLSession代理简介 #import "ViewController.h" @interface ViewController ()<NSURLSessionDataDelegate> @end @implementation ViewController - (void)viewDidLoad {
[super viewDidLoad]; }
//这是为了测试而建立的点击屏幕事件。
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ //代理 测试 NSURL * url = [NSURL URLWithString:@"http://localhost/login.php?username=haha&password=123"]; //创建自定义Session NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc]init]]; NSURLSessionTask * task = [session dataTaskWithURL:url];
//开启任务
[task resume]; }
#pragma mark - deleDate
//接受到服务器响应
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
//__FUNCTION__ c语言字符串用s
NSLog(@"%s",__FUNCTION__); //允许服务器回传数据
completionHandler(NSURLSessionResponseAllow); }
//接受服务器回传的数据可能执行多次
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data{ NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]); }
//请求成功或者失败
-(void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error{
NSLog(@"%@",error);
}
@end
上面简单介绍了一下
然后我们来看一个demo
其中下载文件的地址,读者可以自己配置
//
// ViewController.m
// NSURLSession大文件下载
//
// #import "ViewController.h" @interface ViewController ()<NSURLSessionDownloadDelegate> @property (nonatomic, strong) NSURLSessionDownloadTask * task; @property (nonatomic, strong) NSData * resumeData; @property (nonatomic, strong) NSURLSession * session; @end @implementation ViewController - (IBAction)start:(id)sender { NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[[NSOperationQueue alloc] init]]; self.session = session; self.task = [session downloadTaskWithURL:[NSURL URLWithString:[@"http://192.168.1.200/DOM解析.mp4"stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]]; [self.task resume];
} - (IBAction)pause:(id)sender { //暂停就是将任务挂起 [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) { //保存已下载的数据
self.resumeData = resumeData;
}];
} - (IBAction)resume:(id)sender { //可以使用ResumeData创建任务 self.task = [self.session downloadTaskWithResumeData:self.resumeData]; //开启继续下载
[self.task resume]; } - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib. NSLog(@"%@",NSSearchPathForDirectoriesInDomains(, , ));
} /* 监测临时文件下载的数据大小,当每次写入临时文件时,就会调用一次 bytesWritten 单次写入多少
totalBytesWritten 已经写入了多少
totalBytesExpectedToWrite 文件总大小 */ - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { //打印下载百分比
NSLog(@"%f",totalBytesWritten * 1.0 / totalBytesExpectedToWrite); } //下载完成 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location { NSString * cachesPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename]; NSFileManager * mgr = [NSFileManager defaultManager]; [mgr moveItemAtURL:location toURL:[NSURL fileURLWithPath:cachesPath] error:NULL]; } - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { NSLog(@"%@",error);
} - (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
} @end
网络热恋之NSURLSession的更多相关文章
- IOS网络请求之NSURLSession使用
前言: 无论是Android还是ios都离不开与服务器交互,这就必须用到网络请求,记得在2013年做iOS的时候那时候用的ASIHTTPRequest框架,现在重新捡起iOS的时候ASIHTTPReq ...
- 网络第三节——NSURLSession
有的程序员老了,还没听过NSURLSession有的程序员还嫩,没用过NSURLConnection有的程序员很单纯,他只知道AFN. NSURLConnection在iOS9被宣布弃用,NSURLS ...
- 网络请求 __ NSURLSession
首先配置into.plist文件 1. 添加 App Transport Security Settings , Type栏自动变为Dictionary 2. 点击左边箭头,使之向下,点击右边加号,添 ...
- swift开发网络篇—利用NSURLSession 发送GET和POST请求
说明:本文示例代码发送的请求均为http请求,需要对info.plist文件进行配置.如何配置,请参考https://github.com/HanGangAndHanMeimei/iOS9Adapta ...
- 网络热恋之SDWebImage
SDWebImage-master 是一个非常强大的三方. 当需要应用SDWeb时把文件夹里的SDWebImage文件夹放入工程里. 在需要使用网络获取图片的文件里进入头文件#import " ...
- 网络&热恋NSURLConnection代理及GET¥POST请求
1.NSURLConnection代理下载设置在本地的身骑着白马MP3 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional ...
- iOS开发——网络Swift篇&NSURLSession加载数据、下载、上传文件
NSURLSession加载数据.下载.上传文件 NSURLSession类支持三种类型的任务:加载数据.下载和上传.下面通过样例分别进行介绍. 1,使用Data Task加载数据 使用全局的 ...
- iOS 网络编程:NSURLSession
NSURLSession类和相关的类提供很多API来下载HTTP的内容.这些API提供多种delegate协议来支持验证和执行后台下载任务. 1 URL Session 设计概念 Session中的任 ...
- 网络热恋之json解析
现在的app开发很少有用到XML解析的了,主流的则是JSON. // // ViewController.m // CX-JSON解析(三方JSONKit-master) #import " ...
随机推荐
- SpringMVC详细示例
一.SpringMVC基础入门,创建一个HelloWorld程序 0.框架结构 1.首先,导入SpringMVC需要的jar包. 2.添加Web.xml配置文件中关于springmvc的配置 < ...
- ES6模块的import和export用法总结
ES6之前以前出现了js模块加载的方案,最主要的是CommonJS和AMD规范.commonjs前者主要应用于服务器,实现同步加载,如nodejs.AMD规范应用于浏览器,如requirejs,为异步 ...
- “Win10 UAP 开发系列”之主题模式切换
微软动作真是快,本来想写WP8.1RT系列,结果刚整理了一点就出Win10 UAP了.不过还好RT到Win10的差别还不算太大.前两天参加了Win10开发极客秀,虽然没获奖,不过在韦恩卑鄙的帮助下顺利 ...
- silverlight制作虚线的边框
<Grid><Grid HorizontalAlignment="Center" VerticalAlignment="Center" x:N ...
- iOS学习笔记——iOS高级控件
UITableView UITableView的样式有两种,一种是Grouped(左图),另一种是Plain(右图),如下图,它的属性是style,类型为UITableViewStyle,枚举值分别是 ...
- Jquery获取checkbox属性checked为undefined
说明:本文来自新浪博客,因为无法收藏,故直接copy过来备注,以后好查询 原网址:http://blog.sina.com.cn/s/blog_6810dfc20101jddq.html 使用jQue ...
- SingalR--介绍
什么是SignalR? ASP.NET SignalR是为简化开发开发人员将实时web内容添加到应用程序过程而提供的类库.实时web功能指的是让服务器代码可以随时主动推送内容给客户端,而不是让服务器等 ...
- Telerik UI For WinForms--关于RadGridView的列排序
在使用RadGridView绑定数据后,我希望属性的显示顺序按继承层次显示,但实际是相反的.下面示例两个类: public class A { public string Astr { get; se ...
- win10下vs2015创建asp,net core项目并运行在ubuntu14.04下
上文说了.net core程序在win10与ubuntu下运行,用的是示例程序(https://github.com/aspnet/cli-samples),今天用vs2015 构建asp.net c ...
- Delphi 收藏
日前整理仓库,翻出了一些 Delphi 产品,以前购买的 Delphi 都有实体产品,包含说明书.光碟片.还有一些广告文宣,而且相当厚实,版本的演进,从外包装也能感受到,到目前的 XE5 版,只剩一个 ...