如果你繼承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更多的是失敗*授權*而不是認證(「認證成功(如果有的話),但你不能這樣做」)。但沒關係,那是另一個問題。再次感謝你的幫助。 –