工程目录说明:
1.Request:文件夹下存储网络请求的类,下面会给出具体的实现
2.Config:就是工程的配置文件
3.Resource:就是工程的资源文件,下面有图片资源和Storyboard文件资源
4.Tools是:工具文件类,存放工具类,比如数据正则匹配等。
5.Vender:存放第三方类库
6.Model:这个就不多说了
7.ViewController:存放ViewController类资源文件,也就是View层
8.ViewModel:存放各种业务逻辑和网络请求
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
//
// 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
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
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
DEMO的:GitHub下载地址:https://github.com/lizelu/MVVM
https://www.cnblogs.com/yulang314/p/5104064.html