#import "ViewController.h"
#import "DownLoadOperation.h"
#import "AppInfo.h"
@interface ViewController ()
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (nonatomic, strong) NSOperationQueue *queue;
@property (nonatomic, copy) NSString *currentURL;
@property (nonatomic, strong) NSMutableDictionary *operationCache;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
NSArray *data = [AppInfo appInfoList];
AppInfo *app = data[arc4random_uniform(data.count)];
if (![app.icon isEqualToString:self.currentURL] && self.currentURL) {
DownLoadOperation *operation = self.operationCache[self.currentURL];
[operation cancel];
[self.operationCache removeObjectForKey:self.currentURL];
}
self.currentURL = app.icon;
DownLoadOperation *op = [DownLoadOperation downloadOperationWithURLString:app.icon finish:^(UIImage *image) {
self.imageView.image = image;
[self.operationCache removeObjectForKey:app.icon];
}];
[self.queue addOperation:op];
[self.operationCache setObject:op forKey:app.icon];
}
- (NSMutableDictionary *)operationCache {
if (_operationCache == nil) {
_operationCache = [NSMutableDictionary dictionary];
}
return _operationCache;
}
- (IBAction)cancel:(id)sender {
[self.queue cancelAllOperations];
NSLog(@"%@",self.operationCache);
}
- (NSOperationQueue *)queue {
if (_queue == nil) {
_queue = [[NSOperationQueue alloc]init];
}
return _queue;
}
@end
#import <UIKit/UIKit.h>
@interface DownLoadOperation : NSOperation
+ (instancetype)downloadOperationWithURLString:(NSString *)URLString finish:(void(^)(UIImage *image))finish;
@end
#import "DownLoadOperation.h"
#import "NSString+Path.h"
@interface DownLoadOperation ()
@property (nonatomic, copy) NSString *URLString;
@property (nonatomic, copy) void(^finish)(UIImage *image);
@end
@implementation DownLoadOperation
- (void)main {
@autoreleasepool {
NSAssert(self.finish != nil, @"完成回调不能为空");
NSURL *url = [NSURL URLWithString:self.URLString];
NSString *path = [self.URLString appendCache];
NSData *data = [NSData dataWithContentsOfFile:path];
if (data) {
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
NSLog(@"沙盒缓存");
UIImage *image = [UIImage imageWithData:data];
self.finish(image);
}];
return;
}
data = [NSData dataWithContentsOfURL:url];
if (data) {
NSLog(@"%@",NSHomeDirectory());
[data writeToFile:[self.URLString appendCache] atomically:YES];
}
if (self.isCancelled) {
NSLog(@"操作已经被取消");
return;
}
UIImage *image = [UIImage imageWithData:data];
[[NSOperationQueue mainQueue]addOperationWithBlock:^{
self.finish(image);
}];
}
}
+ (instancetype)downloadOperationWithURLString:(NSString *)URLString finish:(void (^)(UIImage *))finish {
DownLoadOperation *op = [[self alloc]init];
op.URLString = URLString;
op.finish = finish;
return op;
}
@end