//
// 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. 【转】 NoSQL初探之人人都爱Redis:(4)Redis主从复制架构初步探索

    一.主从复制架构简介 通过前面几篇的介绍中,我们都是在单机上使用Redis进行相关的实践操作,从本篇起,我们将初步探索一下Redis的集群,而集群中最经典的架构便是主从复制架构.那么,我们首先来了解一 ...

  2. PHP循环语句基础介绍

    PHP 中的循环语句用于执行相同的代码块指定的次数. 循环 在您编写代码时,您经常需要让相同的代码块运行很多次.您可以在代码中使用循环语句来完成这个任务. 在 PHP 中,我们可以使用下列循环语句: ...

  3. linq 实现动态 orderby

    class Pet { public string Name{get;set;} public int Age{get;set;} } void Main() { Pet[] pets = { }, ...

  4. html5学习笔记(3)--主题结构元素-1

    Article元素 以下为对应代码: <!DOCTYPE html> <html> <head lang="en"> <meta char ...

  5. 【Java每日一题】20161115

    package Nov2016; import java.io.Serializable; public class Ques1115 implements Serializable{ private ...

  6. JAVA多线程和并发基础面试问答(转载)

    JAVA多线程和并发基础面试问答 原文链接:http://ifeve.com/java-multi-threading-concurrency-interview-questions-with-ans ...

  7. opencart二次开发小记

    在controller中如果要调用model中数据或说方法可以这样写 $this->load->model('catalog/information');//model中的informat ...

  8. MYSQL 解锁与锁表

    解锁 第一种 show processlist; 找到锁进程,kill id ; 第二种 mysql>UNLOCK TABLES; 锁表 锁定数据表,避免在备份过程中,表被更新 mysql> ...

  9. 代理模式的java实现

    1.  简介 代理模式(Proxy Pattern)是常用设计模式之一.代理模式的定义:Provide a surrogate or placeholder for another object to ...

  10. Play!中使用HTTP异步编程

    本章译者:@Sam Liu (译者未留下自己的主页,请Sam Liu见此文,加入群168013302联系‘大黄蜂@翻译play’) 这一章主要讲解如何运用异步模式实现典型的长连接(long-polli ...