将Url参数添加到所有Restkit请求

时间:2015-01-30 07:49:07

标签: ios objective-c restkit-0.20

它们是一种向所有restkit请求添加一些url参数(如http://api.example.com/v3/object?data=123&info=test)的方法,并将其手动添加到所有

getObjectsAtPath:parameters:success:failure:
getObjectsAtPathForRouteNamed:object:parameters:success:failure:
...

每个请求都应添加info参数。

我实际上是一种方法,使用Method Swizzling。它们是否可以直接使用RestKit进行操作?

1 个答案:

答案 0 :(得分:1)

您有几种方法可以做到这一点:

你可以将RKObjectManager的方法子类化为这样的东西:

-(void)addedParamToGetObjectsAtPath:(NSString*)path parameters:(NSDictionary*)parameters success:(success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult)successBlock failure::^(RKObjectRequestOperation *operation, NSError *error){

NSMutableDictionary* newParams = [NSMutableDictionary new];
if(parameters){
       [newParams addEntriesFromDictionary:parameters];
}
newParams[@"info"]=test;
getObjectsAtPath:(NSString*)path parameters:(NSDictionary*)parameters success:(success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
// Deal with the success here
successBlock(operation, mappingResult);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
//Deal with the error here
errorBlock(operation, error);
}];

或告诉Restkit使用不同的RequestOperationClass

//When configuring RestKit
RKObjectManager *objectManager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:BASE_URL]];
//Some more configuration
//....
[objectManager registerRequestOperationClass:[YourObjectRequestOperation class]];

定义RKObjectRequestOperation的子类,YourObjectRequestOperation

#import "FBObjectRequestOperation.h"

@interface RKHTTPRequestOperation ()
@property (nonatomic, strong, readwrite) NSMutableURLRequest* request;
@end

@implementation FBObjectRequestOperation


- (id)initWithHTTPRequestOperation:(RKHTTPRequestOperation *)requestOperation responseDescriptors:(NSArray *)responseDescriptors
{
NSParameterAssert(requestOperation);
NSParameterAssert(responseDescriptors);

//your method to change the requestOperation

RKHTTPRequestOperation* myRequestOperation = [YourObjectRequestOperation addParametersToRequest:requestOperation];

self = [super initWithHTTPRequestOperation:myRequestOperation responseDescriptors:responseDescriptors];
if (self) {
 //Change headers or any other thing that you need
}

return self;

}

要实际更改requestOperation,您需要从请求中获取url并添加新参数。这将发生在这部分RKHTTPRequestOperation* myRequestOperation = [YourObjectRequestOperation addParametersToRequest:requestOperation];中,我正在努力完成代码。

这适用于您使用对象管理器执行的任何请求。 如果您需要为每个请求动态计算标头,这种技术也非常有用。