下载图片并异步显示更新数据到前台,我们可以有很多种方法,在IOS中提到了两种方法如下:
需要定义一个ImageView和一个Button如下:
@property (retain, nonatomic) IBOutlet UIImageView *imageView;
- (IBAction)download:(id)sender;
第一种方法:
- (IBAction)download:(id)sender {
NSURL *url = [NSURL URLWithString:@"http://img6.cache.netease.com/cnews/2012/6/1/20120601085505e3aba.jpg"];
[NSThread detachNewThreadSelector:@selector(dowork:) toTarget:self withObject:url];
}
-(void) dowork: (NSURL*) url{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSError *error;
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSHTTPURLResponse *response;
NSData* retData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (response.statusCode == 200) {
UIImage* img = [UIImage imageWithData:retData];
[self performSelectorOnMainThread:@selector(refreshUI:) withObject:img waitUntilDone:YES];
}
NSLog(@"d %d", response.statusCode);
[pool drain];
}dowork方法中下载完成后通知UI更新,函数如下
-(void) refreshUI:(UIImage* ) img{
self.imageView.image = img;
}
第二种方法使用GCD来更新UI
- (IBAction)download:(id)sender {
[self blockWork];
}
Button调用block方法来下载并回调async来异步更新UI来显示图片
-(void)blockWork{
dispatch_queue_t queue;
queue = dispatch_queue_create("com.example.operation", NULL);
dispatch_async(queue, ^{
NSString *urlString = @"http://img6.cache.netease.com/cnews/2012/6/1/20120601085505e3aba.jpg";
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]];
UIImage *imge = [UIImage imageWithData:imageData];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = imge;
});
});
使用Block 文档:
http://www.devdiv.com/Blocks编程要点【中文完整翻译版】-article-3205-1.html
本文介绍在iOS环境下,通过定义ImageView和Button,实现图片的异步下载及更新至UI的方法,包括使用NSThread、NSOperation等技术进行操作。
210

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



