项目开发中会请求大量不同的API,若将网络请求三板斧直接写在Controller中会代码十分冗杂,干脆直接将AFNetWorking
和JSONModel
封装到一个全局的Manager单例类中,在Manager类中进行网络请求和数据解析
导入AFNetworking和JSONModel
参考【iOS】AFNetworking的基本使用
创建一个单例类Manager
Manager.h
代码块Block用于传值
#import <Foundation/Foundation.h>
#import "TestModel.h"typedef void(^SuccessBlock)(TestModel* testModel);
typedef void(^ErrorBlock)(NSError* error);@interface Manager : NSObject+ (instancetype)sharedManager;- (void)sendRequestWithURL: (NSString *)urlString success: (SuccessBlock)success failure: (ErrorBlock)failure;@end
Manager.m
这里使用GCD方法实现简单的单例模式
#import "Manager.h"
#import "AFNetworking.h"static Manager* manager = nil;@implementation Manager+ (instancetype)sharedManager {if (!manager) {static dispatch_once_t onceToken;dispatch_once(&onceToken, ^{manager = [[Manager alloc] init];});}return manager;
}- (void)sendRequestWithURL:(NSString *)urlString success:(SuccessBlock)success failure:(ErrorBlock)failure {[[AFHTTPSessionManager manager] GET: urlString parameters: nil headers: nil progress: nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {if (success) {TestModel* testModel = [[TestModel alloc] initWithDictionary: responseObject error: nil];success(testModel);}} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {if (failure) {failure(error);}}];
}@end
Manager的使用
- (void)requestTest {[[Manager sharedManager] sendRequestWithURL: @"https://news-at.zhihu.com/api/4/news/latest" success:^(TestModel * _Nonnull testModel) {NSLog(@"%@", testModel.stories[0]);} failure:^(NSError * _Nonnull error) {if (error) NSLog(@"请求失败");}];
}
请求下来的部分数据:
这样就可以将不同的请求分别写成不同的单例方法,而且代码简单易懂