zoukankan      html  css  js  c++  java
  • 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;
    }
     

    您的资助是我最大的动力!
    金额随意,欢迎来赏!

    如果,您认为阅读这篇博客让您有些收获,不妨点击一下右下角的推荐按钮。
    如果,您希望更容易地发现我的新博客,不妨点击一下绿色通道的关注我

    如果,想给予我更多的鼓励,求打

    因为,我的写作热情也离不开您的肯定支持,感谢您的阅读,我是【往事亦如风】!

  • 相关阅读:
    生活娱乐 工业机器人代替工人装配鼠标键盘
    生活娱乐 工商银行如何查询开户行
    生活娱乐 格力空气能热水器怎么样
    生活娱乐 岛城将开首家机器人餐厅
    生活娱乐 毕业生论文查重技巧
    Windows 老是弹出要自动拨号连接怎么办
    Office 针式打印机如何调节边距
    Office 如何打印彩色照片能取得较好的效果
    西游释厄传如何设置简化出招表
    [ES2019] Use JavaScript ES2019 flatMap to Map and Filter an Array
  • 原文地址:https://www.cnblogs.com/ldnh/p/5281449.html
Copyright © 2011-2022 走看看