做的网站上更改内容改怎么回事,南昌网站seo公司,房屋装修设计图,国字类型网站有哪些内容在之前的项目里#xff0c;我们都是把网络请求写在viewController的viewDidLoad#xff0c;而实际中使用的时候并不能这么简单#xff0c;对于不同的需要#xff0c;我们需要有不同的网络请求。所以我们可以用单例模式创建一个全局的Manager类#xff0c;用实例Manager来执…在之前的项目里我们都是把网络请求写在viewController的viewDidLoad而实际中使用的时候并不能这么简单对于不同的需要我们需要有不同的网络请求。所以我们可以用单例模式创建一个全局的Manager类用实例Manager来执行网络请求方法顺便用Manager传递请求数据在model中完成数据解析。
使用上一篇JSONModel中的代码为例我们现在创建一个新的Manager类然后将网络请求的相关操作封装进去并使用block传值将网络请求的结果传给要用的地方 #import JSONModel.h
#import QianTaoJSONModel.h//用了block传值
//_Nonnull 是 Objective-C 中的一个关键字用于标记变量、参数或返回类型。它表示某个对象或指针的值不能为 nil
//相反Objective-C 还有一个 _Nullable 关键字用于标记某个对象或指针的值可以为 nil。
typedef void (^DataBlock)(QianTaoJSONModel * _Nonnull mainModel);
typedef void (^ErrorBlock)(NSError * _Nonnull error);NS_ASSUME_NONNULL_BEGINinterface Manager : JSONModel (instancetype)sharedManager;
- (void)NetWorkWithData: (DataBlock)dataBlock error: (ErrorBlock) errorBlock;endNS_ASSUME_NONNULL_END #import Manager.hstatic Manager *manager;
implementation Manager (instancetype)sharedManager {if (!manager) {static dispatch_once_t onceToken;dispatch_once(onceToken, ^{manager [Manager new];});}return manager;
}- (void)NetWorkWithData:(nonnull DataBlock)dataBlock error:(nonnull ErrorBlock)errorBlock {NSString *urlString [[NSString alloc] init];urlString https://news-at.zhihu.com/api/4/news/latest;urlString [urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];NSURL *url [NSURL URLWithString:urlString];NSLog(%, urlString);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) {QianTaoJSONModel *t [[QianTaoJSONModel alloc] initWithData:data error:nil];dataBlock(t);} else {errorBlock(error);}}];[dataTask resume];
}end
以上就是Manager的封装。 这时候我们就可以直接使用封装好的网络请求了。在viewController中我们先声明一个test方法在test方法中我们创建Manager对象并打印该对象的数据。在[viewDidLoad]中我们调用该方法即可 #import ViewController.hinterface ViewController ()endimplementation ViewController- (void)viewDidLoad {[super viewDidLoad];[self test];
}- (void)test {[[Manager sharedManager] NetWorkWithData:^(QianTaoJSONModel * _Nonnull mainModel) {NSLog(%, mainModel.top_stories[0]);} error:^(NSError * _Nonnull error) {NSLog(ERROR);}];
}end
结果