IOS開發之---非同步下載顯示圖片

來源:互聯網
上載者:User

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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.