#import
#import
@protocol DownLoadOperationDelegate
- (void)sendImage:(UIImage *)image;
@end
@interface DownLoadOperation : NSOperation
{
NSString *urlString;
}
//@property (nonatomic,copy)void(^finish)(UIImage *image);
@property (nonatomic)id
//下载图片的operation 需要url
- (instancetype)initWithDownLoadMessageURL:(NSString *)url;
@end
#import "DownLoadOperation.h"
@implementation DownLoadOperation
//Operationde 具体操作写在main 里面 startde 时候会执行里面的操作
- (instancetype)initWithDownLoadMessageURL:(NSString *)url
{
self = [super init];
if (self) {
urlString = url;
}
return self;
}
- (void)main
{
NSLog(@".......");
// 具体下载的操作
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
UIImage *image = [UIImage imageWithData:data];
NSLog(@"%@",image);
[self.delegate sendImage:image];
// [[NSNotificationCenter defaultCenter]postNotificationName:@"下载完成" object:image];
// self.imageBlock(image);
}
@end
#import "ViewController.h"
#import "DownLoadOperation.h"
@interface ViewController ()
{
UIImageView *imageView;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(listenNot:) name:@"下载完成" object:nil];
imageView = [[UIImageView alloc]initWithFrame:self.view.frame];
[self.view addSubview:imageView];
DownLoadOperation *downLoad = [[DownLoadOperation alloc]initWithDownLoadMessageURL:@"http://www.huabian.com/uploadfile/2014/1118/20141118042246536.jpg"];
downLoad.delegate = self;
// downLoad.imageBlock = ^(UIImage *image){imageView.image = image;};
// [downLoad start];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
queue.maxConcurrentOperationCount = 1;
[queue addOperation:downLoad];
}
- (void)sendImage:(UIImage *)image
{
imageView.image = image;
}
//- (void)listenNot:(NSNotification *)sender
//{
// NSLog(@"%@",sender);
//// imageView.image = sender.object;
//}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end