Deepak Chaudhary
Deepak Chaudhary

Reputation: 1761

How to load image asynchronously using UIImageView+AFNetworking in ios

I am using this:

UIImage *image = [UIImage imageWithData: [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://oldmaker.com/glamberry_v2/ios_Loading-Spinners.gif"]]];

but this is taking too much time. I want to use AFNetworking to make loading speed faster.

Any help would be appreciated.

Upvotes: 2

Views: 8849

Answers (5)

Alejandro Iván
Alejandro Iván

Reputation: 4061

No answer seems to handle this completely, so, to have more info...

First of all, you should include the AFNetworking category for UIImageView:

#import "UIImageView+AFNetworking.h"

If you're using CocoaPods, this line should be:

#import <AFNetworking/UIImageView+AFNetworking.h>

After that, you should have at least one UIImageView (I'm going to assume you have an IBOutlet connected):

@property (weak, nonatomic) IBOutlet UIImageView *myImageView;

Then you can load your image in code:

// Define a placeholder image that will be shown while the remote image
// loads. If you don't want a placeholder image, just set it to nil.
// Note that this placeholder image is local (it should be in your
// asset files/collection).
UIImage *myPlaceholderImage = nil; // Or use [UIImage imageNamed:@"..."];

// First, cancel other tasks that could be downloading images.
// If you only do this once, this is probably not needed, but it's not harmful to
// always have it before loading an image with setImageWithURL: and derivatives.
[self.myImageView cancelImageDownloadTask];

// Set up a NSURL for the image you want.
// I'm gonna use this wonderful owl: https://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg
NSURL *imageURL = [NSURL URLWithString:@"https://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg"];

// Check if the URL is valid
if ( imageURL ) {
    // The URL is valid so we'll use it to load the image asynchronously.
    // Pass the placeholder image that will be shown while the
    // remote image loads.
    [self.myImageView setImageWithURL:imageURL
                     placeholderImage:myPlaceholderImage];
}
else {
    // The imageURL is invalid, just show the placeholder image.
    dispatch_async(dispatch_get_main_queue(), ^{
        self.myImageView.image = myPlaceholderImage;
    });
}

If, for any reason, you need to do something to the remote image before delivering it to the UIImageView, you can use the setImageWithURLRequest:placeholderImage:success:failure: method. I'm going to transform the received UIImage to another UIImage in template mode, so it will be colored with the tintColor of the UIImageView (of course, this image of an owl will not look good, this should be a plain icon with transparency):

UIImage *placeholderImage = nil;

NSURL *imageURL = [NSURL URLWithString:@"https://www.smashingmagazine.com/wp-content/uploads/2015/06/10-dithering-opt.jpg"];

if ( imageURL ) {
    // Check NSURLRequestCachePolicy enumeration for other values.
    // 60 seconds in timeoutInterval is the default for iOS.
    NSURLRequest *imageRequest = [NSURLRequest requestWithURL:imageURL 
                                                  cachePolicy:NSURLRequestReloadIgnoringCacheData
                                              timeoutInterval:60.0f];

    [self.myImageView cancelImageDownloadTask];

    // We'll keep a weak reference to our UIImageView so it won't have
    // any possibility of being retained by our success/failure blocks.
    __weak typeof(self.myImageView) weakImageView = self.myImageView;

    dispatch_async(dispatch_get_main_queue(), ^{
        [self.myImageView setImageWithURLRequest:imageRequest
                                placeholderImage:placeholderImage
                                         success:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, UIImage * _Nonnull image) {
                                                   UIImage *tintedImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
                                                   weakImageView.image  = tintedImage;
                                               }
                                               failure:^(NSURLRequest * _Nonnull request, NSHTTPURLResponse * _Nullable response, NSError * _Nonnull error) {
                                                   weakImageView.image = placeholderImage;
                                               }];
    });

}
else {
    dispatch_async(dispatch_get_main_queue(), ^{
        self.myImageView.image = placeholderImage;
    });
}

And yes, I know this is an old question, but this should serve as reference.

Upvotes: 1

Jiri Zachar
Jiri Zachar

Reputation: 587

you can load async image like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:imageData];
        });
    });

i you need set this image into imageview so try use this:

UIImageView *img = [[UIImageView alloc] initWithFrame:FRAME];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
    dispatch_async(queue, ^{
        NSData * imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            UIImage *image = [UIImage imageWithData:imageData];
            img.image = image;
            img.contentMode = UIViewContentModeScaleAspectFill;
        });
    });

Upvotes: 3

Stefan
Stefan

Reputation: 1335

Haneke will also do the job.

[imageView hnk_setImageFromURL:url];

And if you want to load with AFNetworking:

[self.someImageView setImageWithURL:[NSURL URLWithString:@"urlOfImage"]];

Upvotes: 0

DHEERAJ
DHEERAJ

Reputation: 1468

You can use SDWebImage

It supports asynchronous downloading as well as caching.

Usage

Just #import the UIImageView+WebCache.h header

  [imgView sd_setImageWithURL:Url_Of_The_Image placeholderImage:[UIImage imageNamed:@"Sampleimage.png"]];

Upvotes: 10

arturdev
arturdev

Reputation: 11039

#import "UIImageView+AFNetworking.h"  

//...
[self.imageView setImageWithURL:[NSURL URLWithString:@"image_url"]];

Upvotes: 4

Related Questions