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


   

你可能感兴趣的:(IOS开发之---异步下载显示图片)