iOS - Cell网络请求数据加载

待实现需求:使用网络请求数据加载UITableViewCell。

数据准备

返回JSON数据的URL

{
    "reason": "成功的返回", 
    "result": {
        "stat": "1", 
        "data": [
            {
                "uniquekey": "ef422a4971e5d8f31b16e0397aaaf240", 
                "title": "小雪节气,多吃这4种补锌食物,营养还美味,全家都喜欢", 
                "date": "2020-11-21 13:46", 
                "category": "头条", 
                "author_name": "生活+", 
                "url": "https://mini.eastday.com/mobile/201121134608754.html", 
                "thumbnail_pic_s": "https://04imgmini.eastday.com/mobile/20201121/20201121134608_da2ecc65570afb52d9d38e4e5bec387e_2_mwpm_03200403.jpg", 
                "thumbnail_pic_s02": "http://04imgmini.eastday.com/mobile/20201121/20201121134608_da2ecc65570afb52d9d38e4e5bec387e_1_mwpm_03200403.jpg", 
                "thumbnail_pic_s03": "http://04imgmini.eastday.com/mobile/20201121/20201121134608_da2ecc65570afb52d9d38e4e5bec387e_3_mwpm_03200403.jpg"
            }, 
            ...
        ]
    }, 
    "error_code": 0
}

我们需要利用data数组中的数据来加载UITableViewCell,Cell的设计如动图效果展示此处不做代码介绍。

我们利用JSON转Obj来使用网络数据,所以需要设计一个对象类来管理数据对象。

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface ListItem : NSObject

@property (nonatomic, strong, readwrite) NSString *category;
@property (nonatomic, strong, readwrite) NSString *date;
@property (nonatomic, strong, readwrite) NSString *authorName;
@property (nonatomic, strong, readwrite) NSString *picUrl;
@property (nonatomic, strong, readwrite) NSString *title;
@property (nonatomic, strong, readwrite) NSString *articleURL;
@property (nonatomic, strong, readwrite) NSString *uniqueKey;
// 利用字典数据配置数据对象
- (void)configWithDictionary:(NSDictionary *)dictionary;

@end

NS_ASSUME_NONNULL_END
#import "ListItem.h"

@implementation ListItem

- (void)configWithDictionary:(NSDictionary *)dictionary {
    self.category = [dictionary objectForKey:@"category"];
    self.picUrl = [dictionary objectForKey:@"thumbnail_pic_s"];
    self.date = [dictionary objectForKey:@"date"];
    self.title = [dictionary objectForKey:@"title"];
    self.uniqueKey = [dictionary objectForKey:@"uniquekey"];
    self.articleURL = [dictionary objectForKey:@"url"];
    self.authorName = [dictionary objectForKey:@"author_name"];
}

@end

创建网络加载器

设计一个网络加载器类,实现网络加载数据回调。

#import <Foundation/Foundation.h>

@class ListItem;

NS_ASSUME_NONNULL_BEGIN

typedef void(^listLoaderFinishBlock)(BOOL success, NSArray<ListItem *> *dataArray);


@interface ListLoader : NSObject

- (void)loadListDataWithFinishBlock:(listLoaderFinishBlock)finishBlock;

@end

NS_ASSUME_NONNULL_END
#import "ListLoader.h"
#import "ListItem.h"

@implementation ListLoader

- (void)loadListDataWithFinishBlock:(listLoaderFinishBlock)finishBlock {
	// 创建URL
    NSString *urlString = @"http://v.juhe.cn/toutiao/index?type=top&key=97ad001bfcc2082e2eeaf798bad3d54e";
    NSURL *listURL = [NSURL URLWithString:urlString];
  	
  	// 创建会话
    NSURLSession *session = [NSURLSession sharedSession];
  
  	// 创建DataTask任务
    NSURLSessionDataTask *dataTask = [session dataTaskWithURL:listURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"get error: %@", error.localizedDescription);
        } else {
            NSError *jsonError;
            // 将data转为JSON格式对象
            id jsonObj = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
            if (jsonError) {
                NSLog(@"get error: %@", jsonError.localizedDescription);
            } else {
            	// 取到data数组数据
                NSArray *dataArray = [(NSDictionary *)([((NSDictionary *)jsonObj) objectForKey:@"result"]) objectForKey:@"data"];
                // 将JSON对象转为数据对象
                NSMutableArray *listItemArray = @[].mutableCopy;
                for (NSDictionary *info in dataArray) {
                    ListItem *listItem = [[ListItem alloc] init];
                    [listItem configWithDictionary:info];
                    [listItemArray addObject:listItem];
                }
                // 主线程执行刷新逻辑
                dispatch_async(dispatch_get_main_queue(), ^{
                            if (finishBlock) {
                                finishBlock(error == nil, listItemArray.copy);
                            }
                });
            }
        }
        
    }];
    
    // 恢复任务
    [dataTask resume];
}

@end

执行网络请求

注意循环引用,刷新UITableView。

@interface ViewController () <UITableViewDataSource, UITableViewDelegate, NormalTableViewCellDelegate>

@property(nonatomic, strong, readwrite) UITableView *tableView;
@property(nonatomic, strong ,readwrite) NSArray *dataArray;
@property(nonatomic, strong, readwrite) ListLoader *listLoader;

@end

@implementation ViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.tableView = [[UITableView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.view addSubview:_tableView];
    
    self.listLoader = [[ListLoader alloc] init];
    __weak typeof(self) weakSelf = self;
    [self.listLoader loadListDataWithFinishBlock:^(BOOL success, NSArray<ListItem *> * _Nonnull dataArray) {
            __strong typeof(self) strongSelf = weakSelf;
        strongSelf.dataArray = dataArray;
        [strongSelf.tableView reloadData];
    }];
    // Do any additional setup after loading the view.
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值