UI课程17 图片异步下载、KVO

1.网络请求流程
1)创建一个request
2)建立urlConnection,解析数据
3)使用数据
2.封装的图片下载器
在用到的地方直接用下载器名调用即可。
WXImageDownLoader.h中:

#import 
#import 

//代理方法
@protocol  WXImageDownLoaderDelegate<NSObject>

- (void)imageDownLoaderDownLoadImage:(UIImage *)image;

@end


//定义一个block块
typedef void (^imageDownloadImageURLString)(UIImage *image);


@interface WXImageDownLoader : NSObject

//同步下载
+ (UIImage *)imageDownLoaderDownLoadImageWithImageURLString:(NSString *)imageURL;

//异步下载
//代理
+ (void)imageDownLoaderDownLoadImageWithImageURLStringByAsynchronous:(NSString *)imageURL delegate:(id)delegate;

//block
+(void)imageDownLoaderDownLoadImage:(NSString *)imageURL block:(imageDownloadImageURLString)block;

@end

WXImageDownLoader.m中:

@implementation WXImageDownLoader

//同步下载
+ (UIImage *)imageDownLoaderDownLoadImageWithImageURLString:(NSString *)imageURL {

    //1.根据传进来的网址字符串创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]];

    //2.使用Data对象接受同步请求的图片数据
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    //3.返回请求后的图片对象
    return [UIImage imageWithData:data];
}

//异步下载(代理)
+ (void)imageDownLoaderDownLoadImageWithImageURLStringByAsynchronous:(NSString *)imageURL delegate:(id)delegate{

    //1.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]];
    //2.链接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        UIImage *image = [UIImage imageWithData:data];

        //代理对象执行此方法
        if (delegate && [delegate respondsToSelector:@selector(imageDownLoaderDownLoadImage:)]) {
            [delegate imageDownLoaderDownLoadImage:image];
        }

    } ];
}

//block
+(void)imageDownLoaderDownLoadImage:(NSString *)imageURL block:(imageDownloadImageURLString)block{

    //
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:imageURL]];

    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

        UIImage *image = [UIImage imageWithData:data];

        //block传值
        block(image);
    }];

}

你可能感兴趣的:(UI)