Search code examples
iosswiftrestrestkit

Cannot map single object


I am having an issue using RestKit.

I have an endpoint, items/ where I can GET an array of items. Here is a sample return:

[
  { item_id: 1 },
  { item_id: 2 },
  { item_id: 3 }
]

I can also do something like items/<item_id> to get only one item. For example, if I GET items/2 I will get this:

{ item_id: 2 }

I mapped like this:

let itemsResponseMapping: RKObjectMapping = RKObjectMapping(withClass: MyItem.self)
itemsResponseMapping.addAttributeMappingsFromDictionary(["item_id" : "itemId"])

let responseDescriptor = RKResponseDescriptor(
        mapping: itemsResponseMapping,
        method: RKRequestMethod.GET,
        pathPattern: "items",
        keyPath: nil,
        statusCodes: RKStatusCodeIndexSetForClass(RKStatusCodeClass.Successful)
)
objectManager.addResponseDescriptor(responseDescriptor);

So, to request I'll do this:

RKObjectManager.sharedManager().getObjectsAtPath(
        ENDPOINT,
        parameters: nil,
        success: {(operation: RKObjectRequestOperation!, mapping: RKMappingResult!) -> Void in
            //whatever
        },
        failure: {(operation: RKObjectRequestOperation!, error: NSError!) -> Void in
            //whatever
        }

When ENDPOINT is "items" then it succeeds. But when ENDPOINT is "items/2", then I get a No response descriptors match the response loaded. If I check operation.HTTPRequestOperation.responseString, then I see the fetch was successful, but the problem is that it's not mapping it.

What am I missing here??

Edit: I should add that I don't own the backend, and the fix should be done in iOS.


Solution

  • You need to add a second response descriptor with a path pattern of items/:id because the simple path pattern doesn't match.