有下面这么一段代码,代理也遵守了,回调方法也写了但是总是不走代理方法,真是让人纠结啊 。
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的时候多读读注释也是好的。?