harvey_slash harvey_slash - 1 year ago 127
iOS Question

RestKit , Intercept failed request/ retry if it was caused due to token Expiration

I have a class called API helper with a Method that looks like this:

+(RKObjectManager*) getRestObjectManager{
AFHTTPClient *client = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
// initialize RestKit
RKObjectManager *objectManager = [[RKObjectManager alloc] initWithHTTPClient:client];

return objectManager;

And I will create classes like API_User , API_Group etc. Each of these classes will have methods like

+(void)getDetails:(void (^)(User* user) )onSuccess{

//fetch object manager from api helper and perform request, on success, call the onSuccess block from the function parameter.

onSuccess(user); //if it was successful, i will create a user object and //return.


There will be several methods like getDetails , each which require an authentication token to be sent to work. The token can expire , and needs to be refreshed.

How do I :

Define some sort of an interceptor in API helper , so that when a request fails , it will fetch a new token (my token expired response itself provides a new token) ,and retry the request that had failed? I don't want to handle this for each and every endpoint that I define.

Answer Source

What I did was Extend RKObject Manager and handled failures there like so :

@implementation MYOWNObjectManager

#pragma mark - RKObjectManager Overrides
- (void)getObjectsAtPath:(NSString *)path parameters:(NSDictionary *)parameters success:(void (^)(RKObjectRequestOperation *operation, 
RKMappingResult *mappingResult))success failure:(void (^)(RKObjectRequestOperation *operation, NSError *error))failure {  
    [super getObjectsAtPath:path parameters:parameters success:success failure:^(RKObjectRequestOperation *operation, NSError *error) {
//check if failure was due to token expiry, if yes call the code to refresh token. otherwise just call   failure(operation, error);

[super getObjectsAtPath:path parameters:parameters success:success failure:failure]; //this line performs the request again. 

This snippet is for GET only. You will also need to override PUT/POST etc with the same logic

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download