iOS如何获取网络图片(一)

static NSString * baseUrl = @"http://192.168.1.123/images/";

 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    SXTShopCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
   
    SXTShop * shop = self.dataList[indexPath.row];
   
    cell.shop = shop;
   
    //为了避免重复加载的问题,创建了downloadImage,downloadImage属于数据源,当tableview滚动的时候就可以给cell的数据赋值
   
    if (shop.downloadImage) {
       
        //如果下载过,直接从内存中获取图片
        cell.iconView.image = shop.downloadImage;
       
    } else {
      
        //设置默认图片
        cell.iconView.image = [UIImage imageNamed:@"defaultImage"];
       
        //如果未下载过,开启异步线程
        NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^{
           
            //模拟网络延时
            [NSThread sleepForTimeInterval:1];
           
            //通过url获取网络数据
            NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",baseUrl,shop.shop_image]]];
           
            //将数据装换为图片
            UIImage * image = [UIImage imageWithData:data];
           
            //如果有图片
            if (image) {
               
                //通知model,将图片赋值给downloadImage,以便下次从内存获取
                shop.downloadImage = image;

                //获取主队列,更新UI
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                   
                    //刷新第indexPath单元的表格
                    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
               
                }];
            }
        }];
        //将请求加入全局队列
        [self.queue addOperation:op];
       
    }

    return cell;
}
 

 

posted @ 2016-03-15 22:04  往事亦如风  阅读(801)  评论(0编辑  收藏  举报