分享

使用GCD处理非UI相关的异步任务 Object-C异步多线程加载网络图片

 ccccshq 2014-03-11

两个核心方法:dispatch_async和dispatch_async_f,分别对应Block Objects方法和C Functions方法。
我们举一个场景来进行:

当我们需要从网络下载一个图片,可以将这个下载工作丢到一个异步线程里面,然后当图片下载完毕后,我们再交给主线程,让主线程去显示这个图片。在这种场景下,我们就需要甬道异步任务了。这里也涉及到了之前提到的__block方式操作本地资源。

代码演示如下:


01.dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
02.dispatch_async(concurrentQueue, ^{
03.__block UIImage *image = nil;
04.dispatch_sync(concurrentQueue, ^{
05./* Download the image here */
06.});
07.dispatch_sync(dispatch_get_main_queue(), ^{
08./* Show the image to the user here on the main queue*/
09.});
10.});

下面看一个具体的代码实现:


01.- (void) viewDidAppear:(BOOL)paramAnimated{
02.dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
03.dispatch_async(concurrentQueue, ^{
04.__block UIImage *image = nil;
05.dispatch_sync(concurrentQueue, ^{
06./* Download the image here */
07./* iPad's image from Apple's website. Wrap it into two lines as the URL is too long to fit into one line */
08.NSString *urlAsString = @"http://images.apple.com/mobileme/features"\ "/images/ipad_findyouripad_20100518.jpg";
09.NSURL *url = [NSURL URLWithString:urlAsString];
10.NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
11.NSError *downloadError = nil;
12.NSData *imageData = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:&downloadError];
13.if (downloadError == nil && imageData != nil){
14.image = [UIImage imageWithData:imageData]; /* We have the image. We can use it now */
15.}
16.else if (downloadError != nil){
17.NSLog(@"Error happened = %@", downloadError);
18.}
19.else
20.{
21.NSLog(@"No data could get downloaded from the URL.");
22.}
23.});
24. 
25.dispatch_sync(dispatch_get_main_queue(), ^{
26./* Show the image to the user here on the main queue*/
27.if (image != nil){
28./* Create the image view here */
29.UIImageView *imageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
30./* Set the image */
31.[imageView setImage:image];
32./* Make sure the image is not scaled incorrectly */
33.[imageView setContentMode:UIViewContentModeScaleAspectFit];
34./* Add the image to this view controller's view */
35.[self.view addSubview:imageView];
36.} else {
37.NSLog(@"Image isn't downloaded. Nothing to display.");
38.}
39.});
40.});
41.}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多