下載圖片並非同步顯示更新資料到前台,我們可以有很多種方法,在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