作者在早期的readme中写到他的动机,当他刚开始写iOS的应用程序的时候,在UITbaleView上设置从web拿图片,苹果没有提供API。
作者当时搜索了很多的资料,大多数都是使用的NSURLConnection来实现的,这虽然能够工作,但是响应速度还是很慢,于是经过尝试,发现NSOperation来处理非常的快速,不会卡顿。
使用用户缓存目录而不是ducment目录,以防止缓存在iTunes中来回同步。
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
documents,应用中用户数据可以放在这里,iTunes备份和恢复的时候会包含此目录;
Library/Caches,存放缓存文件,iTunes不会备份此目录,此目录下文件不会在应用退出后被删除。
用一个UIImageView分类来替代BJCAWebImageView,这样集成的时候就更简单了。
//UIImageView+WebCache.h
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UIImageView (WebCache)
-(void)setImageWithURL:(NSURL *)url;
@end
NS_ASSUME_NONNULL_END
//UIImageView+WebCache.m
#import "UIImageView+WebCache.h"
#import "UIImageHlper.h"
@implementation UIImageView (WebCache)
-(void)setImageWithURL:(NSURL *)url
{
UIImageHlper *helper = nil;
if ([self.subviews count] > 0)
{
helper = [self.subviews objectAtIndex:0];
}
if (helper == nil)
{
helper = [[UIImageHlper alloc] initWithDelegate:self];
[self addSubview:helper];
}
[helper cancel];
if (helper.placeHolderImage == nil)
{
helper.placeHolderImage = self.image;
}
else
{
self.image = helper.placeHolderImage;
}
UIImage *cachedImage = [helper imageWithURL:url];
if (cachedImage)
{
self.image = cachedImage;
}
else
{
[helper downloadWithURL:url];
}
}
@end
//UIImageHlper.h
#import <UIKit/UIKit.h>
#import "BJCAWebImageDownloader.h"
NS_ASSUME_NONNULL_BEGIN
@interface UIImageHlper : UIView
{
UIImageView *delegate;
BJCAWebImageDownloader *downloader;
}
@property (nonatomic, strong) UIImage *placeHolderImage;
-(instancetype)initWithDelegate:(UIImageView *)aDelegate;
-(void)cancel;
-(UIImage *)imageWithURL:(NSURL *)url;
-(void)downloadWithURL:(NSURL *)url;
@end
NS_ASSUME_NONNULL_END
//UIImageHlper.m
#import "UIImageHlper.h"
#import "BJCAImageCache.h"
@implementation UIImageHlper
-(instancetype)initWithDelegate:(UIImageView *)aDelegate
{
if(self = [super init])
{
delegate = aDelegate;
self.hidden = YES;
}
return self;
}
-(UIImage *)imageWithURL:(NSURL *)url
{
return [[BJCAImageCache sharedImageCache] imageFromKey:[url absoluteString]];
}
-(void)downloadWithURL:(NSURL *)url
{
downloader = [BJCAWebImageDownloader downloaderWithURL:url target:self action:@selector(downloadFinishedWithImage:)];
}
-(void)downloadFinishedWithImage:(UIImage *)anImage
{
delegate.image = anImage;
[[BJCAImageCache sharedImageCache] storeImage:anImage forKey:[downloader.url absoluteString]];
downloader = nil;
}
-(void)cancel
{
[downloader cancel];
downloader = nil;
}
@end