ios 如何使用 UIImageView+AFNetworking 异步加载图片

How to load image asynchronously using UIImageView+AFNetworking in ios

我正在使用这个:

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

但这花费了太多时间。我想用 AFNetworking 让加载速度更快。

如有任何帮助,我们将不胜感激。

#import "UIImageView+AFNetworking.h"  

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

您可以使用SDWebImage

它支持异步下载和缓存。

用法

只需#import UIImageView+WebCache.h header

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

Haneke 也会完成这项工作。

[imageView hnk_setImageFromURL:url];

如果您想使用 AFNetworking 加载:

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

您可以像这样加载异步图像:

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];
        });
    });

我需要将这张图片设置到 imageview 中,所以尝试使用这个:

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;
        });
    });

似乎没有答案可以完全解决这个问题,因此,要了解更多信息...

首先,您应该为 UIImageView 添加 AFNetworking 类别:

#import "UIImageView+AFNetworking.h"

如果你使用的是 CocoaPods,这一行应该是:

#import <AFNetworking/UIImageView+AFNetworking.h>

在那之后,你应该至少有一个 UIImageView(我假设你有一个 IBOutlet 连接):

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

然后您可以在代码中加载图像:

// 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;
    });
}

如果出于任何原因,您需要在将远程图像传送到 UIImageView 之前对远程图像进行 某些操作,您可以使用 setImageWithURLRequest:placeholderImage:success:failure:方法。我将在模板模式下将收到的 UIImage 转换为另一个 UIImage,因此它将使用 UIImageViewtintColor 进行着色(当然,这张图像owl 看起来不太好,这应该是透明的普通图标):

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;
    });
}

是的,我知道这是一个老问题,但这应该作为参考。