From d452afdb544f6c22b1ca08ec427234ff4b6ee19f Mon Sep 17 00:00:00 2001 From: DreamPiggy Date: Tue, 6 Apr 2021 15:00:52 +0800 Subject: [PATCH] Ensure the invalid URLSeesion will receive the cancel callback and does not trigger the any exception from framework --- SDWebImage/Core/SDWebImageDownloader.m | 7 ++++--- SDWebImage/Core/SDWebImageDownloaderOperation.m | 7 +++++++ 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/SDWebImage/Core/SDWebImageDownloader.m b/SDWebImage/Core/SDWebImageDownloader.m index 9fd1ad4d..2eeb05e4 100644 --- a/SDWebImage/Core/SDWebImageDownloader.m +++ b/SDWebImage/Core/SDWebImageDownloader.m @@ -140,11 +140,12 @@ static void * SDWebImageDownloaderContext = &SDWebImageDownloaderContext; } - (void)dealloc { - [self.session invalidateAndCancel]; - self.session = nil; - [self.downloadQueue cancelAllOperations]; [self.config removeObserver:self forKeyPath:NSStringFromSelector(@selector(maxConcurrentDownloads)) context:SDWebImageDownloaderContext]; + + // Invalide the URLSession after all operations been cancelled + [self.session invalidateAndCancel]; + self.session = nil; } - (void)invalidateSessionAndCancel:(BOOL)cancelPendingOperations { diff --git a/SDWebImage/Core/SDWebImageDownloaderOperation.m b/SDWebImage/Core/SDWebImageDownloaderOperation.m index 1fbff7ba..1de1e7e9 100644 --- a/SDWebImage/Core/SDWebImageDownloaderOperation.m +++ b/SDWebImage/Core/SDWebImageDownloaderOperation.m @@ -194,6 +194,13 @@ typedef NSMutableDictionary SDCallbacksDictionary; } } + if (!session.delegate) { + // Session been invalid and has no delegate at all + [self callCompletionBlocksWithError:[NSError errorWithDomain:SDWebImageErrorDomain code:SDWebImageErrorInvalidDownloadOperation userInfo:@{NSLocalizedDescriptionKey : @"Session delegate is nil and invalid"}]]; + [self reset]; + return; + } + self.dataTask = [session dataTaskWithRequest:self.request]; self.executing = YES; }