我正在使用的 REST 服务有两种不同的响应模式。
{
success: true,
data: { //all data goes here}
}
或者
{
success: false,
error: "Error",
message: "some message"
}
我正在尝试将 RESTKit 配置为返回我为存储错误响应而创建的某个错误对象,以及为 success=true 情况配置的类(基于 URL)。
我正在尝试使用 RKDynamicMapping 根据“成功”的价值来完成此任务。
- (RKDynamicMapping *)createCompatibleMapping:(NSDictionary *)successDictionary withClass:(Class) class{
NSMutableDictionary *withSuccessDictionary = [NSMutableDictionary dictionaryWithDictionary:successDictionary];
[withSuccessDictionary addEntriesFromDictionary:@{@"success" : @"success"}];
RKObjectMapping *successMapping = [RKObjectMapping mappingForClass:class];
[successMapping addAttributeMappingsFromDictionary:withSuccessDictionary];
RKObjectMapping *restErrorMapping = [RKObjectMapping mappingForClass:[RESTErrorObject class]];
[restErrorMapping addAttributeMappingsFromDictionary:@{@"success" : @"success", @"error" : @"errorString", @"message" : @"message"}];
RKDynamicMapping *dynamicMapping = [RKDynamicMapping new];
[dynamicMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"success" expectedValue:[NSNumber numberWithBool:YES ] objectMapping:successMapping]];
[dynamicMapping addMatcher:[RKObjectMappingMatcher matcherWithKeyPath:@"success" expectedValue:[NSNumber numberWithBool:NO ] objectMapping:restErrorMapping]];
return dynamicMapping;
}
然后我将它添加到这样的响应描述符中:
RKResponseDescriptor * cardDetailsResponseDescriptor2 = [RKResponseDescriptor responseDescriptorWithMapping:cardDetailsResponseMapping method:RKRequestMethodGET
pathPattern:@"services/details/:cardNumber" keyPath:@"data"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[_objectManager.router.routeSet addRoute:[RKRoute routeWithName:@"getCardDetailsRoute" pathPattern:@"services/details/:cardNumber" method:RKRequestMethodGET]];
然后我打电话
[self.objectManager getObjectsAtPathForRouteNamed:@"getCardDetailsRoute" object:card parameters:@{@"token" : authToken} success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
我知道这是一个很大的帖子,可能很难理解。感谢您的耐心:D 对我应该做什么感到困惑。
更改 REST API 并不是一个真正的选择。