1.封装一个GET异步网络请求的类 – ImageDownLoader(继承于NSObject)
它的作用是用 URL 去 网络上 请求 data 至于它为什么叫ImageDownLoader 是因为主要用它去请求图片
现用get异步的代理方法 因此设置data 和 connection两个属性
不过 虽然能从ImageDownLoader类内部得到data 但无法将它传出来进行赋值 所以通过协议方法可将其穿出来 当然 数据请求可以是成功的 也可以是失败的 成功则传出data 失败则传出error 所以需写两个协议方法
// 协议
@protocol ImageDownLoaderDelegate <NSObject>
// 请求成功
- (void)imageDownLoadSucceedWithData:(NSData *)data;
// 请求失败
- (void)imageDownLoadFailedWithError:(NSError *)error;
@end
// 接口部分
@interface ImageDownLoader : NSObject
@property (nonatomic, retain) NSMutableData *data;
@property (nonatomic, retain) NSURLConnection *connection;
// 写了协议当然要设置代理属性
@property (nonatomic, assign) id<ImageDownLoaderDelegate> delegate;
// 自定义初始化方法 用于传入网络字符串 以及 代理
// 前者是为了进行网络请求 后者是为了在初始化的同时设置好协议的代理
- (instancetype)initWithUrl:(NSString *)url delegate:(id<ImageDownLoaderDelegate>)delegate;
// 单独写一个开始请求的方法 这样 网络链接类 开始进行网络请求的时机就不受到限制
- (void)start;
// 同上
- (void)cancel;
@end
实现部分:
// 遵守connection的两个协议
@interface ImageDownLoader () <NSURLConnectionDataDelegate, NSURLConnectionDelegate>
@end
@implementation ImageDownLoader
- (void)dealloc
{
[_connection release];
[_data release];
[super dealloc];
}
// 实现初始化方法 传入网址 当然就是去请求了
- (instancetype)initWithUrl:(NSString *)url delegate:(id<ImageDownLoaderDelegate>)delegate
{
self = [super init];
if (self) {
// 先给自己的ImageDownLoaderDelegate协议设置个代理
_delegate = delegate;
// 获取网址对象
NSURL *Newurl = [NSURL URLWithString:url];
// 获取请求
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:Newurl cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
// 给请求体设置个标识符
[request setHTTPMethod:@"get"];
// 获取网址链接 暂不开始请求 需要时进行
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
return self;
}
// connection的几个代理方法
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
// 如果请求失败 那么让代理把error传出去
if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDownLoadFailedWithError:)]) {
[_delegate imageDownLoadFailedWithError:error];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 接收到服务器的响应信息后要初始化data来接受数据了
self.data = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// data是一段段传入的 所以需将这些零碎的data拼接起来
[self.data appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 请求完成后 让代理把data传出去
if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDownLoadSucceedWithData:)]) {
[_delegate imageDownLoadSucceedWithData:self.data];
}
}
// connection在这个方法里开始请求
- (void)start
{
[self.connection start];
}
// connection在这个方法里中断请求
- (void)cancel
{
[self.connection cancel];
}
@end