Browse Source

Optimizing cancel image download and let task to be canceled really. (#4407)

* optimizing cancel image download task

* update test case
Kinarobin 5 years ago
parent
commit
a1f208b79e
2 changed files with 22 additions and 1 deletions
  1. 21 0
      Tests/Tests/AFImageDownloaderTests.m
  2. 1 1
      UIKit+AFNetworking/AFImageDownloader.m

+ 21 - 0
Tests/Tests/AFImageDownloaderTests.m

@@ -512,6 +512,27 @@
     [self waitForExpectationsWithCommonTimeout];
 }
 
+- (void)testThatCancelImageDownloadItShouldCancelImmediately {
+    [self.downloader.imageCache removeAllImages];
+    
+    NSString *imageURLString = @"https://secure.gravatar.com/avatar/5a105e8b9d40e1329780d62ea2265d8a?d=identicon";
+    AFImageDownloadReceipt *receipt = [self.downloader
+                                       downloadImageForURLRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:imageURLString]]
+                                       success:nil
+                                       failure:nil];
+    [self.downloader cancelTaskForImageDownloadReceipt:receipt];
+
+    XCTestExpectation *expectation = [self expectationWithDescription:@"Image download should be cancelled immediately"];
+    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
+        UIImage *cacheImage = [self.downloader.imageCache imageWithIdentifier:imageURLString];
+        XCTAssertNil(cacheImage);
+        [expectation fulfill];
+    });
+    
+    [self waitForExpectationsWithCommonTimeout];
+}
+
+
 #pragma mark - Threading
 - (void)testThatItAlwaysCallsTheSuccessHandlerOnTheMainQueue {
     XCTestExpectation *expectation = [self expectationWithDescription:@"image download should succeed"];

+ 1 - 1
UIKit+AFNetworking/AFImageDownloader.m

@@ -333,7 +333,7 @@
             }
         }
 
-        if (mergedTask.responseHandlers.count == 0 && mergedTask.task.state == NSURLSessionTaskStateSuspended) {
+        if (mergedTask.responseHandlers.count == 0) {
             [mergedTask.task cancel];
             [self removeMergedTaskWithURLIdentifier:URLIdentifier];
         }