#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
//NSObject依赖于UIKit,
//1.声明一个block方法
typedef void (^ImageDownladerBlock) (UIImage *image);
@interface ZYImageDownloader : NSObject
+(void)downloadImageWithURLString:(NSString *)imageURL
block:(ImageDownladerBlock)block;
@end
====================
@interface ZYImageDownloader ()
@property(nonatomic,strong) UIImage *image;
@end
@implementation ZYImageDownloader
#pragma mark 异步block传值
+(void)downloadImageWithURLString:(NSString *)imageURL
block:(ImageDownladerBlock)block
{
//获取URL并创建请求对象
NSURLRequest *request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:imageURL]];
//发送异步请求数据消息
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
//得到图片数据
UIImage *image = [UIImage imageWithData:data];
//2.调用block传值
//利用block传值--
block(image);
}];
}
@end
===================================================================
@interface ViewController ()<ZYPhotoProtocol>
@property (weak, nonatomic) IBOutlet UIImageView *photo;
@end
@implementation ViewController
#pragma mark 封装图片下载
- (IBAction)photoFengZhuang:(id)sender {
//2.定义block内部实现细节
[ZYImageDownloader downloadImageWithURLString:IMG_SYN block:^(UIImage *image) {
_photo.image = image;
}];
}