Skip to content

Instantly share code, notes, and snippets.

@manmal
Last active August 27, 2017 17:31
Show Gist options
  • Select an option

  • Save manmal/5038010 to your computer and use it in GitHub Desktop.

Select an option

Save manmal/5038010 to your computer and use it in GitHub Desktop.
Very minimalistic fade-in implementation for AFNetworking's UIImageView category. Thanks to @myellow and @merowing_.
#import <AFNetworking.h>
@interface UIImageView (AFNetworkingFadeInAdditions)
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage fadeInWithDuration:(CGFloat)duration;
@end
#import "UIImageView+AFNetworkingFadeInAdditions.h"
@implementation UIImageView (AFNetworkingFadeInAdditions)
- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholderImage fadeInWithDuration:(CGFloat)duration {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPShouldHandleCookies:NO];
[request addValue:@"image/*" forHTTPHeaderField:@"Accept"];
__weak typeof (self) weakSelf = self;
[self setImageWithURLRequest:request placeholderImage:placeholderImage success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
if (!request) // image was cached
[weakSelf setImage:image];
else
[UIView transitionWithView:weakSelf duration:duration options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
[weakSelf setImage:image];
} completion:nil];
} failure:nil];
}
@end

Add AFNetworking to your project (eg. via cocoapods.org), copy these two files into your project, then

#import UIImageView+AFNetworkingFadeInAdditions.h

and use it like this:

[imageView setImageWithURL:myNSURL placeholderImage:someUIImageOrNil fadeInWithDuration:0.2f];
@rrenna
Copy link

rrenna commented Jan 18, 2016

After tweaking your example, it seems to be that:

if (!request) // image was cached

should be changed to:

if (!response) // image was cached

AFNetworking returns a nil response, not a nil request when retrieved from the cache.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment