- , , HTTPSessionManager :
typedef void(^AuthenticationCallback)(NSString *updatedAuthToken, NSError *error);
typedef void(^AuthenticationBlock)(AuthenticationCallback);
@interface MYHTTPSessionManager : AFHTTPSessionManager
@property (nonatomic, copy) AuthenticationBlock authenticationBlock;
@end
@implementation MYHTTPSessionManager
- (NSURLSessionDataTask *)dataTaskWithRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLResponse *response, id responseObject, NSError *error))completionHandler {
void (^callback)(NSString *, NSError *) = ^(NSString *tokenString, NSError *error) {
if (tokenString) {
NSMutableURLRequest *mutableRequest = [request mutableCopy];
[mutableRequest addValue:AuthorizationHeaderValueWithTokenString(tokenString) forHTTPHeaderField:@"Authorization"];
NSURLSessionDataTask *task = [super dataTaskWithRequest:[mutableRequest copy] completionHandler:completionHandler];
[task resume];
} else {
completionHandler(nil, nil, error);
}
};
void (^reauthCompletion)(NSURLResponse *, id, NSError *) = ^(NSURLResponse *response, id responseObject, NSError *error){
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSInteger unauthenticated = 401;
if (httpResponse.statusCode == unauthenticated) {
if (self.authenticationBlock != NULL) {
self.authenticationBlock(callback); return;
}
}
completionHandler(response, responseObject, error);
};
return [super dataTaskWithRequest:request completionHandler:reauthCompletion];
}
@end