I am using RestKit to drive interactions with my web server. I am trying to use routing to POST an Event object to the server with an image attached to it. The code is as follows:
RKObjectManager *manager = [RKObjectManager sharedManager];
RKObjectMapping *map = [self eventMapping];
manager.serializationMIMEType = RKMIMETypeFormURLEncoded;
map.rootKeyPath = @"event";
[manager.mappingProvider setSerializationMapping:map forClass:[Event class]];
[manager.router routeClass:[Event class] toResourcePath:@"/v1/events.json" forMethod:RKRequestMethodPOST];
[manager postObject:event delegate:self block:^(RKObjectLoader *loader){
RKObjectMapping *serMap = [[[RKObjectManager sharedManager] mappingProvider] serializationMappingForClass:[Event class]];
NSError *error = nil;
NSDictionary *d = [[RKObjectSerializer serializerWithObject:event mapping:serMap] serializedObject:&error];
RKParams *p = [RKParams paramsWithDictionary:d];
[p setData:[event imageData] MIMEType:@"image/jpeg" forParam:@"image"];
loader.params = p;
}];
If I create an instance of RKParams using the serialized Event object, then add the image data and assign it as the RKObjectLoader’s params property, all the properties become one massive serialized string. There must be a way to upload an image without the massive string serialization.
I have also tried having an NSData property that is mapped to some attribute, converting a UIImage into NSData along the way, but RestKit complains that it can’t be mapped. Has anyone done this before?
I did something very similar and it worked out just fine. I realize your question is about why RKObjectSerializer isn’t working the way you expect, but maybe it is something else with your setup. I’m posting my code to give a clean example of something that does work. That said, after reading the RKObjectSerializer documentation, I don’t see why you couldn’t initialize your RKParams that way instead of setting them directly as I do in my example.
Router setup:
Mapping setup:
The post: (notice since I built up all my params in the block my object is just a dummy instance to trigger the proper routing and mapper).
Server endpoint (Java, Spring MVC)
Server response JSON (note the keyPath of “petPhoto” that corresponds to the mapping setup):
Delegate: