//开始下载
- (IBAction)startDownLoader:(id)sender {
self.imageDownLoader = [[ImageDownLoader alloc] initWithImageURL:kPicURL delegate:self];
}
//实现方法
-(void)imageDownLoader:(ImageDownLoader *)imageDownLoader didSuccessedWithImage:(UIImage *)image
{
self.imageView.image = image;
}
//结束下载
- (IBAction)cancelDownLoader:(id)sender {
[self.imageDownLoader cancel];
}
//初始化方法
-(id)initWithImageURL:(NSString *)imageURL delegate:(id<imageDownLoaderDelegate>)delegate
{
self = [super init];
if (self) {
//给delegate 赋值
self.delegate = delegate;
//进行请求
[self requestImageWithImageURL:imageURL];
}
return self;
}
//取消下载
-(void)cancel
{
[self.connection cancel];
}
-(void)requestImageWithImageURL:(NSString *)imageURL
{
//1.创建URL
//再编码
NSString *newStr = [imageURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//创建
NSURL *url = [NSURL URLWithString:newStr];
//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.请求并设置代理
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
//链接到服务器
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if (_data == nil) {
self.data = [NSMutableData data];
}
}
//获取数据
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
//拼接
[_data appendData:data];
//进行数据操作
}
//下载完成
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//转化图片
UIImage *image = [UIImage imageWithData:_data];
//通知代理 将图片拿走
[_delegate imageDownLoader:self didSuccessedWithImage:image];
}
//给person对象添加观察者
[self.person addObserver:self forKeyPath:@"name" options:(NSKeyValueObservingOptionNew) context:@"西兰花"];
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"keyPath : %@",keyPath);
NSLog(@"object : %@",object);
NSLog(@"change :%@",change);
NSLog(@"context : %@",context);
self.view.backgroundColor = [UIColor colorWithRed:arc4random() % 256 / 255.0 green:arc4random() % 256 / 255.0 blue:arc4random() % 256 / 255.0 alpha:1.0];
}
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[self.nameTf endEditing:YES];
//使用输入框内的名字 给person对象赋值
self.person.name = self.nameTf.text;
//[self.nameTf resignFirstResponder];
}