上篇文章写了如何使用JSONModel,我把网络请求的内容写到了ViewController的viewDidLoad中, 而实际中使用的时候并不能这么简单 对于不同的需要,我们需要有不同的网络请求,所以我们可以用单例模式,创建一个全局的Manage类,用实例Manage来执行网络请求方法,顺便用Manage传递请求数据,在model里完成数据解析。
所使用到的技术
具体示例:
我们还是用知乎日报的接口来举例:
//Manager.h
#import "JSONModel.h"
#import "TestModel.h"
typedef void (^DataBlock) (TestModel* _Nonnull mainViewModel);
typedef void (^ErrorBlock) (NSError* _Nonnull error);
NS_ASSUME_NONNULL_BEGIN
@interface Manager : JSONModel
+ (instancetype)sharedManage;
- (void)NetWorkWithData:(DataBlock) dataBlock error:(ErrorBlock) errorBlock;
@end
NS_ASSUME_NONNULL_END
//Manager.m
//
// Manager.m
// JSONModel
//
// Created by haoqianbiao on 2021/10/11.
//
#import "Manager.h"
static Manager* manager;
@implementation Manager
+ (instancetype)sharedManage {
if(!manager) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
manager = [Manager new];
});
}
return manager;
}
- (void)NetWorkWithData:(DataBlock)dataBlock error:(ErrorBlock)errorBlock {
NSString* string = [NSString stringWithFormat:@"https://news-at.zhihu.com/api/4/news/latest"];
string = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet] ];
NSURL* url = [NSURL URLWithString:string];
NSURLRequest* request = [NSURLRequest requestWithURL:url];
NSURLSession* session = [NSURLSession sharedSession];
NSURLSessionDataTask* dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error == nil) {
TestModel* country = [[TestModel alloc] initWithData:data error:nil];
dataBlock(country);
} else {
errorBlock(error);
}
}];
[dataTask resume];
}
@end
以上是Manager的封装。
// ViewController.m
#import "ViewController.h"
#import "TestModel.h"
#import "Manager.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self test];
}
- (void) test {
[[Manager sharedManage] NetWorkWithData:^(TestModel * _Nonnull mainViewModel) {
NSLog(@"%@", mainViewModel.top_stories[0]);
NSLog(@"请求成功");
} error:^(NSError * _Nonnull error) {
NSLog(@"请求失败");
}];
}
@end
效果展示: