//
// 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的更多相关文章

  1. IOS网络请求之NSURLSession使用

    前言: 无论是Android还是ios都离不开与服务器交互,这就必须用到网络请求,记得在2013年做iOS的时候那时候用的ASIHTTPRequest框架,现在重新捡起iOS的时候ASIHTTPReq ...

  2. 网络第三节——NSURLSession

    有的程序员老了,还没听过NSURLSession有的程序员还嫩,没用过NSURLConnection有的程序员很单纯,他只知道AFN. NSURLConnection在iOS9被宣布弃用,NSURLS ...

  3. 网络请求 __ NSURLSession

    首先配置into.plist文件 1. 添加 App Transport Security Settings , Type栏自动变为Dictionary 2. 点击左边箭头,使之向下,点击右边加号,添 ...

  4. swift开发网络篇—利用NSURLSession 发送GET和POST请求

    说明:本文示例代码发送的请求均为http请求,需要对info.plist文件进行配置.如何配置,请参考https://github.com/HanGangAndHanMeimei/iOS9Adapta ...

  5. 网络热恋之SDWebImage

    SDWebImage-master 是一个非常强大的三方. 当需要应用SDWeb时把文件夹里的SDWebImage文件夹放入工程里. 在需要使用网络获取图片的文件里进入头文件#import " ...

  6. 网络&热恋NSURLConnection代理及GET¥POST请求

    1.NSURLConnection代理下载设置在本地的身骑着白马MP3 - (void)viewDidLoad { [super viewDidLoad]; // Do any additional ...

  7. iOS开发——网络Swift篇&NSURLSession加载数据、下载、上传文件

    NSURLSession加载数据.下载.上传文件   NSURLSession类支持三种类型的任务:加载数据.下载和上传.下面通过样例分别进行介绍.   1,使用Data Task加载数据 使用全局的 ...

  8. iOS 网络编程:NSURLSession

    NSURLSession类和相关的类提供很多API来下载HTTP的内容.这些API提供多种delegate协议来支持验证和执行后台下载任务. 1 URL Session 设计概念 Session中的任 ...

  9. 网络热恋之json解析

    现在的app开发很少有用到XML解析的了,主流的则是JSON. // // ViewController.m // CX-JSON解析(三方JSONKit-master) #import " ...

随机推荐

  1. 【读书笔记】--SQL基础概念复习

    主键:每个表,只能有一个主键,主键不能为NULL,且必须是唯一的.主键最好是由单个列组成,但这不是必须的,主键也可以是由多个列组成,如果表的两个列组合在一起能唯一标识一个行,而单个列不能,则可以将这两 ...

  2. 【转载】HttpWebRequest开启gzip压缩简介

    在用HttpWebRequest对象时,一般我们都没有开启gzip压缩,如果服务端返回的数据比较大,这是我们需要开启gzip压缩,怎么开启呢? 1.给HttpWebRequest对象,添加如下Head ...

  3. 介绍开源的.net通信框架NetworkComms框架 源码分析(五)ReservedPacketType

    原文网址: http://www.cnblogs.com/csdev Networkcomms 是一款C# 语言编写的TCP/UDP通信框架  作者是英国人  以前是收费的 目前作者已经开源  许可是 ...

  4. 11.20 CSS定位智博星网页制作

    <html xmlns="http://www.w3.org/1999/xhtml">   <head>   <meta http-equiv=&qu ...

  5. maven安装与配置(第一天学习笔记)

    Maven下载:http://maven.apache.org/ 1.首先要确保JDK已经安装与配置(注意:用的是apache-maven-3.3.3的JDK1.6不行,我用的是JDK1.8) 2.把 ...

  6. 2015暑假多校联合---Problem Killer(暴力)

    原题链接 Problem Description You are a "Problem Killer", you want to solve many problems. Now ...

  7. percona server 5.7.16正式发布

    继2016年10月12日mysql 5.7.16发布后,percona server 5.7.16终于于11月29日发布了,这是最新版本的5.7系列,可从https://www.percona.com ...

  8. treeview bootstrap 多级下拉树

    bootstrap-treeview.js1是一款强大的树菜单插件,本文演示bootstrap-treeview.js15种不同的调用方法.它可一次性加载数据,也可异步加载.支持Checkbox,se ...

  9. WPF如何实现一款类似360安全卫士界面的程序?(共享源码!)

    以前学习Windows Form编程的时候,总感觉自己做的界面很丑,看到360安全卫士.迅雷等软件的UI设计都非常美观,心里总是憧憬着要是自己能实现这样的UI效果该多好!!!另一个困扰我的问题是,这个 ...

  10. Ocrad.js – JS 实现 OCR 光学字符识别

    Ocrad.js 相当于是 Ocrad 项目的纯 JavaScript 版本,使用 Emscripten 自动转换.这是一个简单的 OCR (光学字符识别)程序,可以扫描图像中的文字回文本. 不像 G ...