搭建简单的网络部分(OC)框架

准备工作

1.文件目录结构示图(按照MVC分层)

文件目录结构图/自定义Cell
  • Controller: CYXOneViewController
  • Model: CYXMenu
  • View: CYXCell

2.使用cocoapods集成第三方框架

  • 注:这里就直接使用cocoapods插件安装第三方框架了

第三方框架
  • 这里要使用到的三方框架包括AFNetworking、MJExtension、SDWebImage
  • 框架用途简介
    • AFNetworking:用于发送网络请求
    • MJExtension:用于把网络返回的JSON格式数据转换为模型属性
    • SDWebImage:用于下载网络图片

基本思路简述

  • 1.在CYXOneViewController中使用AFNetworking发送GET请求,得到服务器返回的JSON格式的数据
  • 2.使用MJExtensionJSON格式的数据转为模型CYXMenu对应的属性
  • 3.在- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;方法内根据索引indexPath.row把每一行Cell的Model属性传递给自定义Cell(CYXCell)
  • 4.在自定义Cell(CYXCell)内接收模型数据并初始化Cell的内部控件
  • 5.不要忘记在AFN框架内的GET请求成功调用的block中刷新TableView的数据

详细实现 上代码

  • 第一步:设计模型属性(CYXMenu.h),这里的属性名根据API文档设计,本Demo只是使用了其中几个简单的
#import <Foundation/Foundation.h>

@interface CYXMenu : NSObject

/** 图片 */
@property (copy, nonatomic) NSString * albums;
/** 标题 */
@property (nonatomic,copy) NSString *title;
/** 材料 */
@property (nonatomic,copy) NSString *ingredients;

@end
  • 第二步:自定义cell(这里使用Xib了)

    • 2.1 拖控件到Xib中(见文件目录结构图)
    • 2.2 在CYXCell.h中定义一个模型属性,用于供外界(CYXOneViewController)访问并传递模型进来。

      #import <UIKit/UIKit.h>
      
      @class CYXMenu;
      
      @interface CYXCell : UITableViewCell
      
      /** 菜单模型 */
      @property (strong, nonatomic) CYXMenu * menu;
      
      @end
    • 2.3 在CYXCell.m中实现menu属性的- (void)setMenu:(CYXMenu *)menu方法,将取到的menu模型值给cell自身的控件赋值
      由于这里需要通过URL下载网络图片,使用到了SDWebImage框架

      #import "CYXCell.h"
        #import "CYXMenu.h"
        #import <UIImageView+WebCache.h>
      
        @interface CYXCell ()
        @property (weak, nonatomic) IBOutlet UIImageView *albumsImageView;
        @property (weak, nonatomic) IBOutlet UILabel *titleLable;
        @property (weak, nonatomic) IBOutlet UILabel *ingredientsLabel;
        @end
      
        @implementation CYXCell
        - (void)setMenu:(CYXMenu *)menu{
      
            _menu = menu;
            // 利用SDWebImage框架加载图片资源
            [self.albumsImageView sd_setImageWithURL:[NSURL URLWithString:menu.albums]];
            // 设置标题
            self.titleLable.text = menu.title;
            // 设置材料数据
            self.ingredientsLabel.text = menu.ingredients;
      
        }
        @end
  • 第三步,到这里我们需要在CYXOneViewController.m内实现 网络数据请求/JSON数据转模型/给自定义cell传递模型数据 的操作
#import "CYXOneViewController.h"
    #import "CYXCell.h"
    #import "CYXMenu.h"
    #import <AFNetworking.h>
    #import <MJExtension.h>

    @interface CYXOneViewController ()

    /** 存放数据模型的数组 */
    @property (strong, nonatomic) NSMutableArray * menus;

    @end

    @implementation CYXOneViewController

    #pragma mark - 全局常量
    // 发送请求URL
    static NSString * const CYXRequestURL = @"http://apis.haoservice.com/lifeservice/cook/query?";
    // 重用cell标识符
    static NSString * const CYXCellID = @"cell";

    #pragma mark - life cycle 生命周期方法

    - (void)viewDidLoad {
        [super viewDidLoad];

        self.tableView.rowHeight = 90;

        // 注册重用Cell
        [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([CYXCell class]) bundle:nil] forCellReuseIdentifier:CYXCellID];

        // 调用加载数据方法
        [self loadData];

        self.view.backgroundColor = [UIColor whiteColor];
    }

    #pragma mark - private methods 私有方法
    /**
     *  发送请求并获取数据方法
     */
    - (void)loadData{

        // 请求参数(根据接口文档编写)
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"menu"] = @"西红柿";
        params[@"pn"] = @"1";
        params[@"rn"] = @"20";
        params[@"key"] = @"2ba215a3f83b4b898d0f6fdca4e16c7c";

        // 在AFN的block内使用,防止造成循环引用
        __weak typeof(self) weakSelf = self;

        [[AFHTTPSessionManager manager] GET:CYXRequestURL parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            NSLog(@"请求成功");

            // 利用MJExtension框架进行字典转模型
            weakSelf.menus = [CYXMenu objectArrayWithKeyValuesArray:responseObject[@"result"]];

            // 刷新数据(若不刷新数据会显示不出)
            [weakSelf.tableView reloadData];

        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            NSLog(@"请求失败 原因:%@",error);
        }];
    }

    #pragma mark - UITableviewDatasource 数据源方法

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return self.menus.count;
    }

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

        CYXCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

        cell.menu = self.menus[indexPath.row];

        return cell;
    }

    #pragma mark - UITableviewDelegate 代理方法

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
        // 点击了第indexPath.row行Cell所做的操作
    }

    @end
  • 到这里只是简单实现了网络数据的请求,还有很多细节,例如下拉/上拉刷新,、cell的点击事件等等,有时间再讨论了。
  • 附:源码github地址
原文地址:https://www.cnblogs.com/fengmin/p/6251087.html