我正在尝试为 编写一个包装器RestKit
,以便所有请求都调用一个函数,该函数又会通过RestKit
.
这是我到目前为止所拥有的:
一个函数将调用我的包装器,如下所示:
NSDictionary *response = [包装器 sendRequestWithURLString:url 方法:@"GET"];
我的包装方法:
+ (NSDictionary *)sendRequestWithURLString:(NSString *)request method:(NSString *)method
{
RKRequestDidFailLoadWithErrorBlock failBlock;
if ([method isEqualToString:@"GET"])
return [self sendGETRequestWithURLString:request withFailBlock:failBlock];
else if ([method isEqualToString:@"POST"])
return [self sendPOSTRequestWithURLString:request withFailBlock:failBlock];
return nil;
}
+ (NSDictionary *)sendGETRequestWithURLString:(NSString *)request withFailBlock:(RKRequestDidFailLoadWithErrorBlock)failBlock {
RKObjectManager *manager = [RKObjectManager sharedManager];
__block NSDictionary *responseDictionary;
[manager loadObjectsAtResourcePath:request usingBlock:^(RKObjectLoader *loader) {
loader.onDidLoadResponse = ^(RKResponse *response) {
[self fireErrorBlock:failBlock onErrorInResponse:response];
RKJSONParserJSONKit *parser = [RKJSONParserJSONKit new];
responseDictionary = [[NSDictionary alloc] initWithDictionary:[parser objectFromString:[response bodyAsString] error:nil]];
};
}];
return responseDictionary;
}
+ (void)fireErrorBlock:(RKRequestDidFailLoadWithErrorBlock)failBlock onErrorInResponse:(RKResponse *)response {
if (![response isOK]) {
id parsedResponse = [response parsedBody:NULL];
NSString *errorText = nil;
if ([parsedResponse isKindOfClass:[NSDictionary class]]) {
errorText = [parsedResponse objectForKey:@"error"];
}
if (errorText)
failBlock([self errorWithMessage:errorText code:[response statusCode]]);
}
}
+ (NSError *)errorWithMessage:(NSString *)errorText code:(NSUInteger)statusCode {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error"
message:@"Please make sure you are connected to WiFi or 3G."
delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alert show];
return nil;
}
这里的问题是当responseDictionary
返回时,该值为 nil,因为onDidLoadResponse
它同时运行时尚未处理。
在这种情况下,设置的最佳方法是responseDictionary
什么?我试图避免调用另一个类的 setter 方法。在这种情况下,我唯一的选择是使用委托,这违背了创建包装类的全部目的,因为 RestKit 调用需要使用委托方法来返回响应?
我能否将我的包装器传递给一个success
可以更新某些本地 ivar 的块?我该怎么做?