在继承RKObjectRequestOperation以检查错误时,如何重试失败的操作?

时间:2013-10-06 21:08:35

标签: ios objective-c restkit restkit-0.20

我已经将RKManagedObjectRequestOperation子类化并覆盖以下方法,

    - (void)setCompletionBlockWithSuccess:(void ( ^ ) ( RKObjectRequestOperation *operation , RKMappingResult *mappingResult ))success failure:(void ( ^ ) ( RKObjectRequestOperation *operation , NSError *error ))failure
{

    [super setCompletionBlockWithSuccess:^void(RKObjectRequestOperation *operation , RKMappingResult *mappingResult) {
        if (success) {
            success(operation, mappingResult);
        }

    }failure:^void(RKObjectRequestOperation *operation , NSError *error) {

        NSInteger statusCode = operation.HTTPRequestOperation.response.statusCode;
        switch (statusCode) {
            case  401: // not authenticated
            {
                MyError* errorResponse = (MyError*)[[error.userInfo objectForKey:@"RKObjectMapperErrorObjectsKey"] firstObject];
                if(errorResponse && [errorResponse.oauth2ErrorCode isEqualToString:@"invalid_token"]){

                    RKObjectRequestOperation* repeatOp = [operation copy];
                    [repeatOp setCompletionBlockWithSuccess:success failure:failure];
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"InvalidTokenFailure" object:repeatOp];

                } else{

                    if (failure) {
                        failure(operation, error);
                    }

                }

            }
                break;

            default:
            {
                if (failure) {
                    failure(operation, error);
                }

            }
                break;
        }
    }];
}

然后在失败通知的观察者中,我发出刷新oauth令牌的请求,并且在成功时,我想再次将原始请求入队,但是在从原始操作中替换了querystring参数之后。

在通知观察员的代码中:

-(void)restRequestFailedWithOperation:(NSNotification*)notification{

    RKManagedObjectRequestOperation *operation = (RKManagedObjectRequestOperation *)notification.object;
    if (operation) {

                // issue token refresh request and in its success block:
                ..... 

                 [[RKObjectManager sharedManager] enqueueObjectRequestOperation:operation];

         }      
}

我没有看到在RKManagedObjectRequestOperation中替换特定查询字符串参数的方法。并且因为原始操作仍然具有旧令牌,所以再次入列它将不起作用。

1 个答案:

答案 0 :(得分:0)

一个解决方法是将附加oauth标记的关注转移到每个传出请求是子类化RKHTTPRequestOperation类并覆盖方法

-(NSURLRequest*)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response{

}

这将确保每个传出请求都将获得最新的oauth令牌。它使您无需使用新请求修改失败的操作。

确保注册子类(MyHTTPRequestOperation),如下所示:

[[RKObjectManager sharedManager] registerRequestOperationClass:[MyHTTPRequestOperation class]];

我不相信这是最好的方法。理想情况下,可以实现RKPaginator类设置的模式。 RKPaginator允许在修改某些查询参数时轻松重复相同的请求。