如果你继承AFHTTPSessionManager
或直接使用一个AFURLSessionManager
你可以使用下面的方法来设置完成一个任务后执行的块:
/**
Sets a block to be executed as the last message related to a specific task, as handled by the `NSURLSessionTaskDelegate` method `URLSession:task:didCompleteWithError:`.
@param block A block object to be executed when a session task is completed. The block has no return value, and takes three arguments: the session, the task, and any error that occurred in the process of executing the task.
*/
- (void)setTaskDidCompleteBlock:(void (^)(NSURLSession *session, NSURLSessionTask *task, NSError *error))block;
只是执行任何你想做的在它的会话的每个任务:
[self setTaskDidCompleteBlock:^(NSURLSession *session, NSURLSessionTask *task, NSError *error) {
if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)task.response;
if (httpResponse.statusCode == 500) {
}
}
}];
编辑: 事实上,如果您需要处理响应对象中返回的错误,则上述方法将不会执行此任务。如果 一种方式,你都继承AFHTTPSessionManager
可能是子类,并设置自定义响应串行与它的过载像responseObjectForResponse:data:error:
:在您的AFHTTPSessionManager
子
@interface MyJSONResponseSerializer : AFJSONResponseSerializer
@end
@implementation MyJSONResponseSerializer
#pragma mark - AFURLResponseSerialization
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
id responseObject = [super responseObjectForResponse:response data:data error:error];
if ([responseObject isKindOfClass:[NSDictionary class]]
&& /* .. check for status or error fields .. */)
{
// Handle error globally here
}
return responseObject;
}
@end
,并设置:
@interface MyAPIClient : AFHTTPSessionManager
+ (instancetype)sharedClient;
@end
@implementation MyAPIClient
+ (instancetype)sharedClient {
static MyAPIClient *_sharedClient = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_sharedClient = [[MyAPIClient alloc] initWithBaseURL:[NSURL URLWithString:MyAPIBaseURLString]];
_sharedClient.responseSerializer = [MyJSONResponseSerializer serializer];
});
return _sharedClient;
}
@end
我还没有想到通知 - 比自定义排队请求更好,也更少侵入。非常感谢!至于验证质询块:我实际上使用的是令牌验证而不是基本验证,所以我猜这是行不通的,对吧?对不起,您提到了401.您会误导奖励问题:“无效令牌”的正确响应代码是什么? 400? –
我不确定“无效令牌”的正确响应代码是什么。也许403更合适。 – Felix
AFAIK 403更多的是失败*授权*而不是认证(“认证成功(如果有的话),但你不能这样做”)。但没关系,那是另一个问题。再次感谢你的帮助。 –