博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NSURLSession不走代理方法的原因
阅读量:7104 次
发布时间:2019-06-28

本文共 1995 字,大约阅读时间需要 6 分钟。

  hot3.png

有下面这么一段代码,代理也遵守了,回调方法也写了但是总是不走代理方法,真是让人纠结啊 。

NSAssert([[self.url absoluteString] length] > 0, @"请输入有效url");    NSURLSession *sharedSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil];    NSURLRequest *request = [NSURLRequest requestWithURL:self.url];    NSURLSessionDownloadTask *task = [sharedSession downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {            } ];    [task resume];- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask      didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWrittentotalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {    NSLog(@"---");}

原来真相竟是如此:

如果你用的是带有block 的方法,那么他就不会执行代理。

这个真心是坑。

如果想让他执行代理可以这么改:

NSURLSessionDownloadTask *downlaodTask = [sharedSession downloadTaskWithRequest:request];

这样就会调用他的代理方法了。

其实调用带 block 的方法就不走代理 apple 也不是没有说明,查看类似带有block 的api 可以发现:

@interface NSURLSession (NSURLSessionAsynchronousConvenience)/* * data task convenience methods.  These methods create tasks that * bypass the normal delegate calls for response and data delivery, * and provide a simple cancelable asynchronous interface to receiving * data.  Errors will be returned in the NSURLErrorDomain,  * see 
. The delegate, if any, will still be * called for authentication challenges. */- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error))completionHandler;

带有block的这些方法其实是 NSURLSession 的一个分类。 注释里有明确说明 :

These methods create tasks that bypass (避开,越过) the normal delegate calls for response and data delivery

so 当我们使用带有block的 data task convenience methods 时就不会再走代理的 response 和 data delivery方法了 。

so 平时我们在用api的时候多读读注释也是好的。?

转载于:https://my.oschina.net/zhxx/blog/879154

你可能感兴趣的文章
织梦修改memberlist标签调用自定义会员模型的会员信息
查看>>
手持机就是对讲机它们有什么区别
查看>>
图片批处理FastStone Photo Resizer
查看>>
C入门程序整体框架图
查看>>
Oracle八大性能视图之v$session
查看>>
junit 实例
查看>>
mount 命令详解
查看>>
玩转php
查看>>
企业私有云应用之使用OZ制作openstack镜像
查看>>
XEN4.0 && KVM性能稳定性测试
查看>>
jetty使用terracotta集群配置
查看>>
比较实用的Cron表达式
查看>>
干系人的管理
查看>>
第五章:浏览器的嗅探和特征侦测
查看>>
去年这时候又辞退了一个老油条,不知道他现在是否在开公司了,可以对比一下混工资的水平...
查看>>
将Vi打造成一个IDE(适合新手和懒人)
查看>>
Solaris目录结构
查看>>
shell自动监控重启tomcat脚本
查看>>
邮箱验证js
查看>>
安装samba软件包失败,求解?
查看>>