8

is there a way to map the parameters in an URL to the results?

I got a rest service where the user can search something by its ID. The path is search/:id The results contains the name and other properties but not the ID.

I could do something like this:

NSArray *array = mappingResult.array;
for (Item *item in array) {
        [item setId:itemID];
}

but I hope there is a nicer way...

Thanks for any hints
Xean

Obenland
  • 856
  • 16
  • 28

2 Answers2

7

You want to use the path pattern you specify in your response descriptor. Then you want to use routing (RKRoute) and metadata during your mapping. The metadata includes a routing section which gives access to the parameters extracted from the URL path.

Some info on metadata here (the docs are a little lacking).

In your mapping you want to use:

@metadata.routing.parameters.id

As the mapping source key path.


To make routing work you need to add the route to your object manager:

[manager.router.routeSet addRoute:...

And then you need to make the request in a way that means the route is used, like getObjectsAtPathForRouteNamed:object:parameters:success:failure:.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • This is the right way. My problem is that `@metadata.routing` dosn't exists. – Obenland Aug 20 '13 at 12:12
  • Are you using `RKRoute`? You will need to show your mappings, response descriptors and route configuration to get more help... – Wain Aug 20 '13 at 12:15
  • My route is `[RKRoute routeWithClass:[Item class] pathPattern:@"search/:id" method:RKRequestMethodGET];`. ResponseDescriptor is the same like @micha-mazaheri wrote. I added the mapping from @Wain with `addAttributeMappingsFromDictionary:` – Obenland Aug 20 '13 at 12:18
  • Ok, so you create a route instance. Are you setting it onto an object manager and how are you triggering the download (to use the route)? – Wain Aug 20 '13 at 12:20
  • Yes: `[objectManager addResponseDescriptorsFromArray:[Item responseDescriptors]];`. I call `[objectManager getObjectsAtPath:path parameters:nil success:(...) failure:(...)];` to start the request. I was debbugging to get the keys of the metadata in `RKMappingOperation`. The mapping is working except of the `@metadata` thing. The path is a string like "search/123" – Obenland Aug 20 '13 at 12:25
  • The `routing` field will only be added when the path is nil (see `RKObjectManager` line 580). So it can't work, right? – Obenland Aug 20 '13 at 12:31
  • With `getObjectsAtPathForRouteNamed:object:parameters:success:failure:` it works perfectly! Thank you! – Obenland Aug 20 '13 at 12:44
1

You probably need to specify the pathPattern and keyPath of your response descriptor::

RKResponseDescriptor *responseDescriptor =
  [RKResponseDescriptor
   responseDescriptorWithMapping:itemMapping
   method:RKRequestMethodAny
   pathPattern:@"search/:id"
   keyPath:@"item"
   statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
Micha Mazaheri
  • 3,481
  • 1
  • 21
  • 26