{
// 终止请求, 最好写在控制器里
[_connection release];
[_data release];
[super dealloc];
}
- (id)initWithImageUrl:(NSString *)imageUrl delegate:(id<ImageDownloaderDelegate>)delegate
{
self = [super init];
if (self) {
// 进行图片的请求
// 1.创建一个NSURL对象
NSURL *url = [NSURL URLWithString:imageUrl];
// 2.用NSURL对象创建一个请求
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
// 3.创建一个链接, 使用代理方法
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
// 4.开启链接
// [_connection start];
// 最好是用这个对象, 可以控制开始或者终止
}
return self;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// 加载完成, 使用代理, 把data传给控制器(因为imageView在控制器创建的)
// 外面设置代理, 并且实现了协议中的方法
// 才能让代理去干活
if (_delegate != nil &&[_delegate respondsToSelector:@selector(imageDownSuccessWithData:)]) {
[_delegate imageDownSuccessWithData:_data];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.data appendData:data];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
self.data = [[[NSMutableData alloc] init] autorelease];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
if (_delegate != nil && [_delegate respondsToSelector:@selector(imageDownFailWithData:)]) {
[_delegate imageDownFailWithData:error];
}
}
.h
// 成功的
- (void)imageDownSuccessWithData:(NSData *)data;
// 失败的
- (void)imageDownFailWithData:(NSError *)error;
@end
@interface ImageDownZuoYe : NSObject<NSURLConnectionDelegate, NSURLConnectionDataDelegate>
@property (nonatomic, retain)NSURLConnection *connection;
// 声明一个代理属性
@property (nonatomic, retain)id<ImageDownloaderDelegate>delegate;
- (void)start;
- (void)cancel;
@property (nonatomic, retain)NSMutableData *data;
// 先声明一个初始化方法
- (id)initWithImageUrl:(NSString *)imageUrl delegate:(id<ImageDownloaderDelegate>) delegate;
本文详细介绍了如何使用NSURLConnection在iOS应用中实现网络请求,包括创建请求、发送请求、处理响应和错误情况的处理。通过实例演示了从URL获取数据的基本流程,并展示了如何将数据传递给控制器进行进一步处理。
210

被折叠的 条评论
为什么被折叠?



