从网络获取数据显示到TableViewCell容易犯的错


   昨晚第一次做用网络接口获取的数据,显示到自己的cell上,犯了很多的错,

总结如下;

1.数据源数组必须首先初始化,一般使用的是懒加载;

2.异步获取网络图片,通过第三方SDWebImage来做

a.首先导入这个包的

#import "UIImageView+WebCache.h"

b.通过这个类的方法设置imageview的图片

//显示网上的图片

    //参数1:需要显示的网络图片的url

    //参数2:占位图片(网络图片还没有下载完之前,imageView上显示的图片)

    //sd_setImageWithURL:placeholderImage:

    [_coverImageView sd_setImageWithURL:[NSURL URLWithString:model.imagePath] placeholderImage:[UIImage imageNamed:@" "]];

    

注意:如果网络图片过大,显示的时候会出现花屏的现象;


3!!!.同步从网络获取的图片是一个URL:比如:http:www.bai.com/xxx.jpg这样子的

在显示在我们的界面上的时候代码要这样写:

//从网络获取图片要用二进制得到url;

    NSURL *url = [NSURL URLWithString:model.cover_image];

    

    NSData *data = [NSData dataWithContentsOfURL:url];

    

    _coverImageView.image = [UIImage imageWithData:data];

2.从网络获取的数据显示在tableViewCell必须要刷新

代码如下:

#pragma mark - 准备数据

- (void)prepareData{

    

    

    //数组的初始化

    self.dataArray = [[NSMutableArray alloc]init];

    

    NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];

    

    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];

    

    NSURL *url = [NSURL URLWithString:path];

    

    NSMutableURLRequest *request = [NSMutableURLRequest

                                    requestWithURL:url];

    

    

    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

        

        

        

        NSDictionary *dict  = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];

        

        NSArray *array = dict[@"data"][@"list"];

        

        for (NSDictionary *dict in array) {

            

            DataModel *myModel = [[DataModel alloc]

                                  initWithDictionary:dict];

           

            

            [self.dataArray addObject:myModel];

            

        }

        //数据刷新!!

        [_tableView reloadData];

        

    }];

    

    [task resume];

   

}


以上就是在从网络获取数据时候容易犯错的地方!!

转载于:https://my.oschina.net/luhoney/blog/667561

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值