IOS开发之---异步下载显示图片

下载图片并异步显示更新数据到前台,我们可以有很多种方法,在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];
    
}



其中调用了dowork函数

-(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


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值