2013-04-30 100 views
1

我试图在REST API上运行通过ID请求查找。我正在使用RestKit 0.20。我有一个Location对象。它有一个id属性。我想对'/ locations /:id'发出GET请求,并以JSON的形式接收完整的对象。 我有后端,它的工作。我现在正在尝试编写iOS客户端代码。Restkit不会将对象属性插入请求URL路径的路径模式

这里是我的:上面的代码运行

RKObjectManager* m = [RKObjectManager sharedManager]; 

RKObjectMapping* lmap = [RKObjectMapping requestMapping]; 
[lmap addAttributeMappingsFromArray:@[@"id"]]; 
RKRequestDescriptor* req = [RKRequestDescriptor requestDescriptorWithMapping:lmap objectClass:[Location class] rootKeyPath:nil]; 
[m addRequestDescriptor:req]; 

Location* l = [[Location alloc] init]; 
l.id = [NSNumber numberWithInt:177]; 
[m getObject:l path:@"locations/:id" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
    NSLog(@"LOADED: %@", [mappingResult firstObject]); 
} failure:^(RKObjectRequestOperation *operation, NSError *error) { 
    NSLog(@"FAILED"); 
}]; 

后Restkit不会替换“:ID:从在Location对象设置的ID属性的路径。

你们有什么想法我做错了吗?

UPDATE:

我有Location类设置请求和响应描述符。我为find_by_id请求添加了一条路由,但它是一条命名路由,而不是一条类路由。当我使用getObject:path:parameters:success:failure方法时,路由器没有填入'id'占位符(不管它是否被命名为'id','object_id','identity'或其他)。

我发现的溶液是这样的:

  1. 继续使用已命名的路由但使用getObjectsAtPathForRouteNamed:对象:参数:成功:失败方法代替
  2. 用户一类路由并继续使用的getObject:路径:参数:成功:失败方法

我是有问题是,使用时NamedRoute像这样:

RKRoute * route = [RKRoute routeWithClass:className pathPattern:path method:RKRequestMethodFromString(method)]; 
[objectManager.router.routeSet addRoute:route]; 

然后使用getObject:path:parameters:success:failure方法查询对象,但不会导致路由器填充URL路径中的任何占位符。

+1

“身份证”是一个Objective- C关键字不要通过关键字调用属性更改属性,映射和关键路径以使用'identity' – Wain 2013-04-30 20:41:13

+0

感谢您的评论!虽然使用'id'时我没有收到任何错误或警告,没有意义,代码的其他部分是正确的,然后呢? – planewalker 2013-04-30 23:35:45

+0

确实没有意义。代码看起来不错,尽管我还没有试过运行它。日志输出是什么意思? – Wain 2013-05-01 06:38:14

回答

5

您正在使用请求描述符,但您没有发出'请求'(PUT/POST)。进行GET时,您需要使用响应描述符。另外,您要创建没有指定类别的映射(所以它链接的是NSDictionary我通常使用响应描述与路由器太喜欢的东西:。

RKObjectManager* m = [RKObjectManager sharedManager]; 

RKObjectMapping* lmap = [RKObjectMapping mappingForClass:[Location class]]; 
[lmap addAttributeMappingsFromArray:@[@"identity"]]; 

RKResponseDescriptor* req = [RKResponseDescriptor responseDescriptorWithMapping:lmap pathPattern:@"locations/:identity" keyPath:nil statusCodes:[NSIndexSet indexSetWithIndex:200]]; 
[m addResponseDescriptor:req]; 

[m.router.routeSet addRoute:[RKRoute routeWithClass:[Location class] pathPattern:@"locations/:identity" method:RKRequestMethodGET]]; 

Location* l = [[Location alloc] init]; 
l.identity = [NSNumber numberWithInt:177]; 

[m getObject:l path:nil parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
    NSLog(@"LOADED: %@", [mappingResult array]); 
} failure:^(RKObjectRequestOperation *operation, NSError *error) { 
    NSLog(@"FAILED"); 
}]; 
+0

非常感谢!我发现了这个问题 - 请参阅我的原始文章中的更新。我会接受你的解决方案,因为它似乎没有我遇到的问题。另外,我应该注意,即使使用'id'作为属性名称,现在一切都正在工作。 – planewalker 2013-05-01 11:38:29