如何取消NSURLSession创建的后台HTTP请求及所有运行中任务?
Hey there, let's break down how to solve this problem. Right now, your code creates data tasks and immediately resumes them without storing references to each task—that's why you can't cancel them later. Here's a straightforward approach to manage and cancel all your active tasks:
1. Store References to Your Tasks
First, you need a way to keep track of every task you create. Add a mutable array property to your class to hold these tasks:
// In your .h file or class extension in .m @property (nonatomic, strong) NSMutableArray<NSURLSessionDataTask *> *activeTasks;
Initialize this array somewhere early (like viewDidLoad or your class's init method):
self.activeTasks = [NSMutableArray array];
2. Track Tasks When Creating Them
Modify your existing loop to add each new task to your array before resuming it. Also, remember to remove the task from the array once it completes (to avoid memory leaks):
for (int i = 0; i < [_urls count]; i++) { // Your existing code to build the NSURLRequest NSURLRequest *request = ...; NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { // Remove the task from tracking once it finishes (success or failure) [self.activeTasks removeObject:task]; // Optional: Skip processing logic if the task was explicitly cancelled if (error && error.code == NSURLErrorCancelled) { return; } // Your original completion handler logic goes here ... }]; // Add the task to our tracking array [self.activeTasks addObject:task]; [task resume]; }
3. Cancel All Active Tasks
Create a method to iterate over your tracked tasks and cancel each one, then clear the array to avoid holding invalid references:
- (void)cancelAllActiveTasks { // Iterate over a copy of the array to prevent issues during removal for (NSURLSessionDataTask *task in [self.activeTasks copy]) { [task cancel]; } [self.activeTasks removeAllObjects]; }
A Quick Note About the Shared Session
Avoid calling [[NSURLSession sharedSession] invalidateAndCancel]; unless you're 100% sure no other parts of your app use the shared session. This method cancels all tasks tied to the shared session, which could break unrelated network calls in your app. Managing your own task references is the safer, more targeted approach.
内容的提问来源于stack exchange,提问作者user1568204

