NSURLSession取消任务

编程入门 行业动态 更新时间:2024-10-23 05:34:57
本文介绍了NSURLSession取消任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我使用以下配置创建新的NSURLSession

if(!self.session){ NSURLSessionConfiguration * config = [NSURLSessionConfiguration backgroundSessionConfiguration:[self uniquieIdentifier]]; config.discretionary = NO; self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; }

然后按下按钮我试图停止所有当前的下载任务。

[[[self session] delegateQueue] setSuspended:YES]; [[self session] invalidateAndCancel];不过我得到的响应委托方法didFinishDownloadingToURL,我很确定没有新的会话或下载任务是在这一点之后创建的。如何停止所有任务的发生?

解决方案

我不建议使用invalidateAndCancel方法导致队列及其标识符保持无效,无法重复使用,直到您重置整个设备。

NSURLSession类参考

我使用此代码取消所有待处理的任务。

- (void)cancelDownloadFiles { [self.session getTasksWithCompletionHandler: (NSArray * dataTasks,NSArray * uploadTasks,NSArray * downloadTasks){ for(NSURLSessionTask * _task in downloadTasks) { [_task cancel]; id< FFDownloadFileProtocol> file = [self getFileDownloadInfoIndexWithTaskIdentifier:_task.taskIdentifier]; [file.downloadTask cancel]; //更改所有相关属性。 file.isDownloading = NO; file.taskIdentifier = -1; file.downloadProgress = 0.0; } }]; cancel = YES; }

I create new NSURLSession with following configs

if (!self.session) { NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfiguration:[self uniquieIdentifier]]; config.discretionary = NO; self.session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; }

and on after pressing a button I am trying to stop all current download tasks.

[[[self session] delegateQueue] setSuspended:YES]; [[self session] invalidateAndCancel];

Nevertheless I get responses in delegate method didFinishDownloadingToURL, and I am pretty sure that no new sessions or download task are created after this point. How to stop all task from happening?

解决方案

I do not reccommend to use invalidateAndCancel method cause the queue and its identifier keeps invalidated and cannot be reused untill you reset the whole device.

NSURLSession class reference

I use this code to cancel all pending tasks.

- (void) cancelDownloadFiles { [self.session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) { for (NSURLSessionTask *_task in downloadTasks) { [_task cancel]; id<FFDownloadFileProtocol> file = [self getFileDownloadInfoIndexWithTaskIdentifier:_task.taskIdentifier]; [file.downloadTask cancel]; // Change all related properties. file.isDownloading = NO; file.taskIdentifier = -1; file.downloadProgress = 0.0; } }]; cancel = YES; }

更多推荐

NSURLSession取消任务

本文发布于:2023-11-08 07:04:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1568679.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NSURLSession

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!