iOS进阶之架构设计MVVM模式实践(11)

1.下面通过一个实例来体会一下MVVM架构模式,下面是该工程的一级目录如下,每层之间的交互是用Block的形式来实现的

iOS进阶之架构设计MVVM模式实践(11)_第1张图片

工程目录说明:

1.Request:文件夹下存储网络请求的类,下面会给出具体的实现

2.Config:就是工程的配置文件

3.Resource:就是工程的资源文件,下面有图片资源和Storyboard文件资源

4.Tools是:工具文件类,存放工具类,比如数据正则匹配等。

5.Vender:存放第三方类库

6.Model:这个就不多说了

7.ViewController:存放ViewController类资源文件,也就是View层

8.ViewModel:存放各种业务逻辑和网络请求

2.详解Request:Request负责网络请求的东西,具体如下:

在这里插入图片描述
NetRequestClass是存放网络请求的代码,本工程用的AF,因为本工程只是一个Demo,所以就只封装了监测网络状态,GET请求,POST请求方法,根据现实需要,还可以封装上传下载等类方法。

NetRequestClass.h中的代码如下:

//
  //  NetRequestClass.h
  //  MVVMTest
  //
  //  Created by 李泽鲁 on 15/1/6.
  //  Copyright (c) 2015年 李泽鲁. All rights reserved.
  //
 
 #import 
 
 @interface NetRequestClass : NSObject
 
 #pragma 监测网络的可链接性
 + (BOOL) netWorkReachabilityWithURLString:(NSString *) strUrl;
 
 #pragma POST请求
 + (void) NetRequestPOSTWithRequestURL: (NSString *) requestURLString
                         WithParameter: (NSDictionary *) parameter
                  WithReturnValeuBlock: (ReturnValueBlock) block
                    WithErrorCodeBlock: (ErrorCodeBlock) errorBlock
                      WithFailureBlock: (FailureBlock) failureBlock;
 
 #pragma GET请求
 + (void) NetRequestGETWithRequestURL: (NSString *) requestURLString
                         WithParameter: (NSDictionary *) parameter
                 WithReturnValeuBlock: (ReturnValueBlock) block
                   WithErrorCodeBlock: (ErrorCodeBlock) errorBlock
                     WithFailureBlock: (FailureBlock) failureBlock;
 
 @end

NetRequestClass.m中的代码如下:

//
   //  NetRequestClass.m
   //  MVVMTest
   //
   //  Created by 李泽鲁 on 15/1/6.
   //  Copyright (c) 2015年 李泽鲁. All rights reserved.
   //
 
   #import "NetRequestClass.h"
 
  @interface NetRequestClass ()
 
  @end
 
  @implementation NetRequestClass
  #pragma 监测网络的可链接性
  + (BOOL) netWorkReachabilityWithURLString:(NSString *) strUrl
  {
      __block BOOL netState = NO;
 
      NSURL *baseURL = [NSURL URLWithString:strUrl];
 
      AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
 
      NSOperationQueue *operationQueue = manager.operationQueue;
 
      [manager.reachabilityManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
          switch (status) {
              case AFNetworkReachabilityStatusReachableViaWWAN:
              case AFNetworkReachabilityStatusReachableViaWiFi:
                  [operationQueue setSuspended:NO];
                  netState = YES;
                  break;
              case AFNetworkReachabilityStatusNotReachable:
                  netState = NO;
              default:
                  [operationQueue setSuspended:YES];
                  break;
          }
      }];
 
      [manager.reachabilityManager startMonitoring];
 
      return netState;
  }
 
  /***************************************
   在这做判断如果有dic里有errorCode
   调用errorBlock(dic)
   没有errorCode则调用block(dic
   ******************************/
 
  #pragma --mark GET请求方式
  + (void) NetRequestGETWithRequestURL: (NSString *) requestURLString
                         WithParameter: (NSDictionary *) parameter
                  WithReturnValeuBlock: (ReturnValueBlock) block
                    WithErrorCodeBlock: (ErrorCodeBlock) errorBlock
                      WithFailureBlock: (FailureBlock) failureBlock
  {
      AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
 
      AFHTTPRequestOperation *op = [manager GET:requestURLString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
          DDLog(@"%@", dic);
 
          block(dic);
 
      } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
          failureBlock();
      }];
 
      op.responseSerializer = [AFHTTPResponseSerializer serializer];
 
      [op start];
 
  }
 
  #pragma --mark POST请求方式
 
  + (void) NetRequestPOSTWithRequestURL: (NSString *) requestURLString
                          WithParameter: (NSDictionary *) parameter
                   WithReturnValeuBlock: (ReturnValueBlock) block
                     WithErrorCodeBlock: (ErrorCodeBlock) errorBlock
                       WithFailureBlock: (FailureBlock) failureBlock
  {
      AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] init];
 
      AFHTTPRequestOperation *op = [manager POST:requestURLString parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
          NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
 
          DDLog(@"%@", dic);
 
          block(dic);
          /***************************************
           在这做判断如果有dic里有errorCode
           调用errorBlock(dic)
           没有errorCode则调用block(dic
          ******************************/
 
     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
         failureBlock();
     }];
 
     op.responseSerializer = [AFHTTPResponseSerializer serializer];
 
     [op start];
 
 }
 
 @end

3.详解Config:创建pch文件,和Config.h文件

//
  //  Config.h
  //  MVVMTest
  //
  //  Created by 李泽鲁 on 15/1/6.
  //  Copyright (c) 2015年 李泽鲁. All rights reserved.
 //
 
  #ifndef MVVMTest_Config_h
 #define MVVMTest_Config_h
 
 //定义返回请求数据的block类型
 typedef void (^ReturnValueBlock) (id returnValue);
 typedef void (^ErrorCodeBlock) (id errorCode);
 typedef void (^FailureBlock)();
 typedef void (^NetWorkBlock)(BOOL netConnetState);
 
 #define DDLog(xx, ...)  NSLog(@"%s(%d): " xx, __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__)
 
 //accessToken
 #define ACCESSTOKEN @"你自己的access_token"
 
 //请求公共微博的网络接口
 #define REQUESTPUBLICURL @"https://api.weibo.com/2/statuses/public_timeline.json"
 
 #define SOURCE @"source"
 #define TOKEN @"access_token"
 #define COUNT @"count"
 
 #define STATUSES @"statuses"
 #define CREATETIME @"created_at"
 #define WEIBOID @"id"
 #define WEIBOTEXT @"text"
 #define USER @"user"
 #define UID @"id"
 #define HEADIMAGEURL @"profile_image_url"
 #define USERNAME @"screen_name"
 
 #endif

4.详解Model:本工程用的是请求公共微博接口我们需要在页面上现实用户的头像,用户名,发布日期,博文,已经隐式的用户ID和微博ID,文件目录结构如下:iOS进阶之架构设计MVVM模式实践(11)_第2张图片

PublicModel中的内容如下:

//
  //  PublicModel.h
  //  MVVMTest
 //
  //  Created by 李泽鲁 on 15/1/8.
  //  Copyright (c) 2015年 李泽鲁. All rights reserved.
  //
 
  #import 
 
 @interface PublicModel : NSObject
 @property (strong, nonatomic) NSString *userId;
 @property (strong, nonatomic) NSString *weiboId;
 @property (strong, nonatomic) NSString *userName;
 @property (strong, nonatomic) NSURL *imageUrl;
 @property (strong, nonatomic) NSString *date;
 @property (strong, nonatomic) NSString *text;
 
 @end

4.详解ViewModel层,本层是最为重要的一层,下面是本层的详细截图,ViewModeClass是所有ViewMode的父类,其中存储着共同部分iOS进阶之架构设计MVVM模式实践(11)_第3张图片

ViewModelClass.h中的内容如下:

//
  //  ViewModelClass.h
  //  MVVMTest
  //
 //  Created by 李泽鲁 on 15/1/8.
  //  Copyright (c) 2015年 李泽鲁. All rights reserved.
  //
 
 #import "ViewModelClass.h"
 @implementation ViewModelClass
 @interface ViewModelClass : NSObject
 
 @property (strong, nonatomic) ReturnValueBlock returnBlock;
 @property (strong, nonatomic) ErrorCodeBlock errorBlock;
 @property (strong, nonatomic) FailureBlock failureBlock;
 
 //获取网络的链接状态
 -(void) netWorkStateWithNetConnectBlock: (NetWorkBlock) netConnectBlock WithURlStr: (NSString *) strURl;
 
 // 传入交互的Block块
 -(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock
                  WithErrorBlock: (ErrorCodeBlock) errorBlock
                WithFailureBlock: (FailureBlock) failureBlock;
 @end

ViewModelClass.m中的内容如下:

//
  //  ViewModelClass.m
  //  MVVMTest
  //
  //  Created by 李泽鲁 on 15/1/8.
  //  Copyright (c) 2015年 李泽鲁. All rights reserved.
  //
 
  #import "ViewModelClass.h"
 @implementation ViewModelClass
 
 #pragma 获取网络可到达状态
 -(void) netWorkStateWithNetConnectBlock: (NetWorkBlock) netConnectBlock WithURlStr: (NSString *) strURl;
 {
     BOOL netState = [NetRequestClass netWorkReachabilityWithURLString:strURl];
     netConnectBlock(netState);
 }
 
 #pragma 接收穿过来的block
 -(void) setBlockWithReturnBlock: (ReturnValueBlock) returnBlock
                  WithErrorBlock: (ErrorCodeBlock) errorBlock
                WithFailureBlock: (FailureBlock) failureBlock
 {
     _returnBlock = returnBlock;
     _errorBlock = errorBlock;
     _failureBlock = failureBlock;
 }
 
 @end

PublicWeiboViewModel.h中的内容如下:

//
  //  PublicWeiboViewModel.h
  //  MVVMTest
  //
  //  Created by 李泽鲁 on 15/1/8.
  //  Copyright (c) 2015年 李泽鲁. All rights reserved.
  //
 
  #import "ViewModelClass.h"
  #import "PublicModel.h"
 
 @interface PublicWeiboViewModel : ViewModelClass
 //获取围脖列表
 -(void) fetchPublicWeiBo;
 
 //跳转到微博详情页
 -(void) weiboDetailWithPublicModel: (PublicModel *) publicModel WithViewController: (UIViewController *)superController;
 @end

PublicWeiboViewModel.m中的内容如下:

//
   //  PublicWeiboViewModel.m
   //  MVVMTest
   //
  //  Created by 李泽鲁 on 15/1/8.
   //  Copyright (c) 2015年 李泽鲁. All rights reserved.
   //
 
   #import "PublicWeiboViewModel.h"
  #import "PublicDetailViewController.h"
 
  @implementation PublicWeiboViewModel
 
  //获取公共微博
  -(void) fetchPublicWeiBo
 {
      NSDictionary *parameter = @{TOKEN: ACCESSTOKEN,
                                 COUNT: @"100"
                                  };
      [NetRequestClass NetRequestGETWithRequestURL:REQUESTPUBLICURL WithParameter:parameter WithReturnValeuBlock:^(id returnValue) {
 
          DDLog(@"%@", returnValue);
          [self fetchValueSuccessWithDic:returnValue];
 
      } WithErrorCodeBlock:^(id errorCode) {
          DDLog(@"%@", errorCode);
          [self errorCodeWithDic:errorCode];
 
      } WithFailureBlock:^{
          [self netFailure];
         DDLog(@"网络异常");
 
      }];
 
  }
 
  #pragma 获取到正确的数据,对正确的数据进行处理
  -(void)fetchValueSuccessWithDic: (NSDictionary *) returnValue
  {
      //对从后台获取的数据进行处理,然后传给ViewController层进行显示
 
      NSArray *statuses = returnValue[STATUSES];
      NSMutableArray *publicModelArray = [[NSMutableArray alloc] initWithCapacity:statuses.count];
 
      for (int i = 0; i ) {
          PublicModel *publicModel = [[PublicModel alloc] init];
 
          //设置时间
          NSDateFormatter *iosDateFormater=[[NSDateFormatter alloc]init];
          iosDateFormater.dateFormat=@"EEE MMM d HH:mm:ss Z yyyy";
 
          //必须设置,否则无法解析
          iosDateFormater.locale=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US"];
          NSDate *date=[iosDateFormater dateFromString:statuses[i][CREATETIME]];
 
          //目的格式
          NSDateFormatter *resultFormatter=[[NSDateFormatter alloc]init];
          [resultFormatter setDateFormat:@"MM月dd日 HH:mm"];
 
          publicModel.date = [resultFormatter stringFromDate:date];
          publicModel.userName = statuses[i][USER][USERNAME];
          publicModel.text = statuses[i][WEIBOTEXT];
          publicModel.imageUrl = [NSURL URLWithString:statuses[i][USER][HEADIMAGEURL]];
          publicModel.userId = statuses[i][USER][UID];
          publicModel.weiboId = statuses[i][WEIBOID];
 
          [publicModelArray addObject:publicModel];
 
      }
 
      self.returnBlock(publicModelArray);
  }
 
  #pragma 对ErrorCode进行处理
  -(void) errorCodeWithDic: (NSDictionary *) errorDic
  {
      self.errorBlock(errorDic);
  }
 
  #pragma 对网路异常进行处理
  -(void) netFailure
  {
      self.failureBlock();
  }
 
  #pragma 跳转到详情页面,如需网路请求的,可在此方法中添加相应的网络请求
  -(void) weiboDetailWithPublicModel: (PublicModel *) publicModel WithViewController:(UIViewController *)superController
  {
      DDLog(@"%@,%@,%@",publicModel.userId,publicModel.weiboId,publicModel.text);
      UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
      PublicDetailViewController *detailController = [storyboard instantiateViewControllerWithIdentifier:@"PublicDetailViewController"];
      detailController.publicModel = publicModel;
      [superController.navigationController pushViewController:detailController animated:YES];
 
  }
 
 @end

6.ViewController层的目录结构如下:

iOS进阶之架构设计MVVM模式实践(11)_第4张图片

运行的最终效果:

iOS进阶之架构设计MVVM模式实践(11)_第5张图片

7.完整目录结构,页面间的业务逻辑,和网络的请求数据是放在ViewModel层的,当然了这也不是绝对的,要灵活把握。

iOS进阶之架构设计MVVM模式实践(11)_第6张图片

DEMO的:GitHub下载地址:https://github.com/lizelu/MVVM

转载

https://www.cnblogs.com/yulang314/p/5104064.html

你可能感兴趣的:(iOS进阶之路)