IOS 图片异步加载 - UIImageView(AFNetworking)

IOS 图片异步加载 - UIImageView(AFNetworking)

说明 :

AFNetworking是一个在进行iOS和Mac OS X 开发时使用广泛的第三方网络类库, 他建立在系统的URL加载系统框架之上, 扩展了Cocoa中更强大, 更高级网络提取功能.它有一个与精心设计的模块化的体系结构, 以及功能丰富的api介绍, 相信使用它会是一件快乐的事情.

UIImageView(AFNetworking)是AFNetworking中一个实现图片异步加载的类, 它是AFNetworking为系统中的UIImageView类添加的类目(Category)用以实现异步加载功能.

文章中尽量不使用或少使用封装, 目的是让大家清楚为了实现功能所需要的官方核心API是哪些(如果使用封装, 会在封装外面加以注释)

UIImageView(AFNetworking)的创建方法及相关知识点

核心API

class : UIImageView(AFNetworking)
delegate : 无
涉及的API : (API的官方详细注释(英文)详见本章结尾)


/** 1. 创建单例图片缓存空间 */
+ (id<AFImageCache>)sharedImageCache
+ (void)setSharedImageCache:(id<AFImageCache>)imageCache

/** 2. 通过url设置imageView */
- (void)setImageWithURL:(NSURL *)url

- (void)setImageWithURL:(NSURL *)url
       placeholderImage:(UIImage *)placeholderImage

/** 3. 通过UIRequest对象请求设置imageView, 参数介绍详见本文结尾的API */ 
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
              placeholderImage:(UIImage *)placeholderImage
                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure

功能实现

思路

  1. 主要是针对UIImageView(AFNetworking)的一些方法和在应用时需要注意的地方进行归纳, 供大家参考和自己学习.

  2. 利用代码来解析说明

(1). 创建UIImageView(AFNetworking)的缓存空间并且找到缓存位置

- (void)createImageCache
{

  /* 在内存中开辟单例空间用于image缓存 */
    id result = [UIImageView sharedImageCache];

    /* 对开辟的空间进行设置用于图片缓存 */
    [UIImageView setSharedImageCache:result];

    NSLog(@"%@", result);

/** 说明: 通过我们输出的这个路径打开文件夹(Library文件夹), 在该文件夹下有一个Caches/'你的工程名'/fsCachedData文件夹, 再打开这个文件夹, 这时就会发现在这个文件夹下有你加载过的照片都会存放在这个空间中. */

}
(2). UIImageView(AFNetworking)因为是在系统类上增加的类目不需要自己创建, 只要将文件拖入工程, 并在要使用的位置引入头文件即可

#import "UIKit+AFNetworking/UIImageView+AFNetworking.h"

/** 说明: 添加到工程的两个文件夹中的文件夹"UIKit+AFNetworking"中, 引入UIImageView+AFNetworking.h */
(3). 直接使用UIImageView(AFNetworking)实现异步加载

- (void)loadImageViewWithAFNetworking {

/* 定义获取URL网络照片字符串 */
    NSURL *urlStr = [NSURL URLWithString:@"http://img2.cache.netease.com/3g/2015/9/18/20150918195439dc844.jpg"];

/* 创建请求对象 */
    NSURLRequest *request = [NSURLRequest requestWithURL:urlStr];

/* 创建一个imageView对象 */
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];

#if 0

/** 方法一:
 * 直接使用url字符串获取照片
 * @prarm urlStr : NSURL对象
 */
    [imageView setImageWithURL:urlStr];

#endif

#if 0

/**方法二:
     * 直接使用URL(例如:http://img2.cache.netease.com/3g/2015/9/18/20150918195439dc844.jpg)异步加载图片, 照片出现之前添加一个占位的背景照片
     * @prarm urlStr : NSURL对象
     * @prarm placeholderImage : UIImage图片对象
     */
    [imageView setImageWithURL:urlStr placeholderImage:[UIImage imageNamed:@"discuss"]];

#endif

#if 1
 /**方法三:
  * 使用URLRequest对象获取照片, 照片在请求后的block块中返回一个UIImage参数用于赋值或其他操作.
  * 参数中得两个block块:分别在请求成功时执行 success:^{},   
                           请求失败时执行 failure:^{}。
  * @prarm request : NSURLRequest请求对象
  * @prarm placeholderImage : UIImage图片对象
  */
    [imageView setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"discuss"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
        /**< 返回值参数
         * @prarm request : NSURLRequest 请求对象
         * @prarm response : NSHTTPURLResponse HTTP响应者对象(包含请求对象和图片信息)
         * @prarm image : 加载成功图片UIImage对象(自带的size尺寸用于自适应高度计算)
         */
        [imageView setImage:image];
    } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
        /**< @prarm error : NSError对象 加载错误的原因代号(例如 : 404) */
    }];

#endif

    /**
     * 取消图片请求操作
     * 可以直接取消本段代码块中在调用这个方法之前的所有异步加载操作(适当的地方慎重使用)
     */
    //[imageView cancelImageRequestOperation];

/* 将定义的imageView添加到ViewController中 */
    [self.view addSubview:imageView];

    /* 内存管理 */
    [imageView release];

    /** 说明 : 以上程序中的参数urlStr字符串和placeholderImage以自己的工程中为准 */

}

API 官方注释(英文)


/** The image cache used to improve image loadiing performance on scroll views. By default, this is an `NSCache` subclass conforming to the `AFImageCache` protocol, which listens for notification warnings and evicts objects accordingly. */

/** 方法 */
+ (id <AFImageCache>)sharedImageCache;

/** Set the cache used for image loading.

 @param imageCache The image cache. */

/** 方法 */
+ (void)setSharedImageCache:(id <AFImageCache>)imageCache;

/** The response serializer used to create an image representation from the server response and response data. By default, this is an instance of `AFImageResponseSerializer`.

 @discussion Subclasses of `AFImageResponseSerializer` could be used to perform post-processing, such as color correction, face detection, or other effects. See https://github.com/AFNetworking/AFCoreImageSerializer */

 /** 属性 */
 @property (nonatomic, strong) id <AFURLResponseSerialization> imageResponseSerializer;

/** Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.

 If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.

 By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`

 @param url The URL used for the image request. */

/** 方法 */
- (void)setImageWithURL:(NSURL *)url;

/** Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.

 If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.

 By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:`

 @param url The URL used for the image request.
 @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. */

/** 方法 */
- (void)setImageWithURL:(NSURL *)url
       placeholderImage:(UIImage *)placeholderImage;

/** Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled.

 If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished.

 If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied.

 @param urlRequest The URL request used for the image request.
 @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes.
 @param success A block to be executed when the image request operation finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the request and response parameters will be `nil`.
 @param failure A block object to be executed when the image request operation finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. */

/** 方法 */
- (void)setImageWithURLRequest:(NSURLRequest *)urlRequest
              placeholderImage:(UIImage *)placeholderImage
                       success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image))success
                       failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error))failure;

/** Cancels any executing image operation for the receiver, if one exists. */

/** 方法 */
- (void)cancelImageRequestOperation;

/** Returns a cached image for the specififed request, if available.

 @param request The image request.

 @return The cached image. */

 /** 方法 */
 - (UIImage *)cachedImageForRequest:(NSURLRequest *)request;
/** Caches a particular image for the specified request.

 @param image The image to cache.
 @param request The request to be used as a cache key. */

 /** 方法 */
 - (void)cacheImage:(UIImage *)image
        forRequest:(NSURLRequest *)request;
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值