diff --git a/AFImageRequest.h b/AFImageRequest.h index a43da5f..2c9833d 100644 --- a/AFImageRequest.h +++ b/AFImageRequest.h @@ -34,5 +34,6 @@ + (void)requestImageWithURLString:(NSString *)urlString options:(AFImageRequestOptions)options block:(void (^)(UIImage *image))block; + (void)requestImageWithURLString:(NSString *)urlString size:(CGSize)imageSize options:(AFImageRequestOptions)options block:(void (^)(UIImage *image))block; - ++ (void)cancelImageRequestOperationsForURLString:(NSString *)urlString; ++ (void)cancelAllImageRequestOperations; @end diff --git a/AFImageRequest.m b/AFImageRequest.m index 7e20e4a..dd282c5 100644 --- a/AFImageRequest.m +++ b/AFImageRequest.m @@ -41,9 +41,9 @@ static NSMutableSet *_cachedRequests = nil; } + (void)requestImageWithURLString:(NSString *)urlString size:(CGSize)imageSize options:(AFImageRequestOptions)options block:(void (^)(UIImage *image))block { - // Append a hash to the image URL so that unique image options get cached separately - NSString *cacheKey = [NSString stringWithFormat:@"%fx%f:%d", imageSize.width, imageSize.height, options]; - NSURL *url = [NSURL URLWithString:[urlString stringByAppendingString:[NSString stringWithFormat:@"#%@", cacheKey]]]; + // Append a hash anchor to the image URL so that unique image options get cached separately + NSString *cacheAnchor = [NSString stringWithFormat:@"%fx%f:%d", imageSize.width, imageSize.height, options]; + NSURL *url = [NSURL URLWithString:[urlString stringByAppendingString:[NSString stringWithFormat:@"#%@", cacheAnchor]]]; if (!url) { if (block) { block(nil); @@ -70,4 +70,28 @@ static NSMutableSet *_cachedRequests = nil; [_operationQueue addOperation:operation]; } ++ (void)cancelImageRequestOperationsForURLString:(NSString *)urlString { + if (!urlString) { + return; + } + + for (AFImageRequestOperation *operation in [_operationQueue operations]) { + NSString *requestURLString = [[[operation request] URL] absoluteString]; + NSRange anchorRange = [requestURLString rangeOfString:@"#" options:NSBackwardsSearch]; + if (anchorRange.location != NSNotFound && [[requestURLString substringToIndex:anchorRange.location] isEqualToString:urlString]) { + if (!([operation isExecuting] || [operation isCancelled])) { + [operation cancel]; + } + } + } +} + ++ (void)cancelAllImageRequestOperations { + for (AFImageRequestOperation *operation in [_operationQueue operations]) { + if (!([operation isExecuting] || [operation isCancelled])) { + [operation cancel]; + } + } +} + @end diff --git a/AFNetworkingExample/Classes/Views/SpotTableViewCell.m b/AFNetworkingExample/Classes/Views/SpotTableViewCell.m index 3149067..2a1c429 100644 --- a/AFNetworkingExample/Classes/Views/SpotTableViewCell.m +++ b/AFNetworkingExample/Classes/Views/SpotTableViewCell.m @@ -80,6 +80,10 @@ #pragma mark - UITableViewCell +- (void)prepareForReuse { + [super prepareForReuse]; + [AFImageRequest cancelImageRequestOperationsForURLString:self.imageURLString]; +} #pragma mark - UIView