MGJRequestManager 是一个基于 AFNetwokring 2.0+ 的 iOS 网络库。
在做项目时,我们通常会在 AFNetworking 的基础上封装一层,加入一些业务逻辑,然后作为统一的 API 层。功能点其实不多,且相对固定和通用,所以我们将常用的功能统一处理,并提供灵活的使用方式,从而诞生了 MGJRequestManager。
MGJRequestManager 目前被用在「蘑菇街」,「小店」等 App 中,并已稳定运行了一段时间。
以「蘑菇街」为例,统计部分会计算请求消耗的时间、每次请求都要发送的参数、根据请求参数值计算 token、缓存请求以便快速呈现等等,MGJRequestManager 都可以方便地处理。
由于需求经常会变化,架构需要非常灵活,以便应对新功能。例如,“发送请求时显示 loading,发送完成后隐藏 loading”这个特性只是利用了现有的接口实现的一个特性。一些常见的需求可以通过对 MGJRequestManager 进行配置来实现。
本着“尽可能简单,但不能更简单”的原则,设计这个类库时,我们希望使用它和理解它都尽可能方便,同时足够灵活,可以应对大多数场景。
主要分为两部分 MGJRequestManagerConfiguration
和 MGJRequestManager
,前者做一些自定义配置,比如请求发送前/后的预处理,baseURL,userInfo等。后者记录下这些信息,在适当的时候消费它们,同时支持针对某些特殊请求做自定义配置。
这就全部了!
pod 'MGJRequestManager'
以“发送请求时显示 loading,发送完成后隐藏 loading”为例
// 1
MGJRequestManagerConfiguration *configuration = [[MGJRequestManagerConfiguration alloc] init];
UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
indicatorView.frame = CGRectMake(self.view.frame.size.width / 2 - 8, self.view.frame.size.height / 2 - 8, 16, 16);
[self.view addSubview:indicatorView];
// 2
configuration.requestHandler = ^(AFHTTPRequestOperation *operation, id userInfo, BOOL *shouldStopProcessing) {
if (userInfo[@"showLoading"]) {
[indicatorView startAnimating];
}
};
// 3
configuration.responseHandler = ^(AFHTTPRequestOperation *operation, id userInfo, MGJResponse *response, BOOL *shouldStopProcessing) {
if (userInfo[@"showLoading"]) {
[indicatorView stopAnimating];
}
};
[MGJRequestManager sharedInstance].configuration = configuration;
// 4
[[MGJRequestManager sharedInstance] GET:@"http://httpbin.org/delay/2"
parameters:nil
startImmediately:YES // 5
configurationHandler:^(MGJRequestManagerConfiguration *configuration){
configuration.userInfo = @{@"showLoading": @YES}; // 6
} completionHandler:^(NSError *error, id<NSObject> result, BOOL isFromCache, AFHTTPRequestOperation *operation) {
[self appendLog:result.description]; // 7
}];
MGJRequestManager
需要与 MGJRequestManagerConfiguration
结合使用,才能发挥出其威力。这个 configuration 可以配置 baseURL
, requestHandler
, responseHandler
等信息,可变部分通常是通过对 MGJRequestManagerConfiguration
进行配置来实现的。你可以全局设置一个 configuration,然后在你单独发送请求时还可以覆盖默认设置。requestHandler
这个 block 会在请求发送前被触发,userInfo
这个参数是 configuration
这个实例的一个属性,为了方便起见,作为参数传给了 requestHandler
。其中一个重要的参数是 *shouldStopProcessing
,如果你在这个 block 中将其设置为 YES
,那么这个请求将不会被发送。responseHandler
这个 block 会在收到服务端的响应后被触发,response
参数有 error
和 result
两个属性,服务端返回的数据都放在 result
属性里,在这里你可以对其进行解析,然后重新设置 response。如果 *shouldStopProcessing
被设置为 YES
,那么 completionHandler
就不会被触发。startImmediately
如果设为 NO
,那么这个请求不会被发送,将来你可以通过调用 -[MGJRequestManager startOperation:]
来发送,或者你也可以将其放入队列中。result
就是 -[MGJResponse result]
, error
是 -[MGJResponse error]
, isFromCache
表示这个结果是否来自缓存。MGJRequestManager 在 MIT 协议下被许可使用。查阅 LICENSE 文件以获取更多信息。