How to map RKClient's RKResponse with an RKObjectMapping - objective-c

I am doing a multi-part posting of image data and some values using RestKit's RKClient like so:
RKParams* params = [RKParams params];
[params setValue:foo.accountId forParam:#"accountId"];
[params setValue:foo.identifier forParam:#"fooId"];
[params setValue:_photoId forParam:#"photoId"];
[params setData:data MIMEType:#"image/png" forParam:#"image"];
[[RKClient sharedClient] post:#"/foo/uploadPhoto" params:params delegate:self];
This works great, and my backend server responds with JSON representation of the server side model object, it look like this:
{"id":"4ee2b4670364720c089e75b9","accountId":"4ebee3469ae2d8adf983c561","fooId":"4ec0983d036463d900841f0b","photoId":"E5B20AF1-9F10-4175-8262-852BDA3DEDE9","filename":"4ebee3469ae2d8adf983c561_4ec0983d036463d900841f0b_E5B20AF1-9F10-4175-8262-852BDA3DEDE9","contentType":"image/png"}
What I need to do now is map this to my client side (iOS) model object. The client side model object is almost the same, but not identical (so using RKJSONParser's objectFromString method is not an option), therefore I have a custom RKObjectMapping defined that handles the mapping. RKClient's delegate only gets a RKResponse, so how can I use the response along with the mapper to get an instance of my client side model object?
Note: To be clear, I am very familiar how this works when using RKObjectManager to post an object and map a response. The unique part of my situation is that I am using RKClient to achieve the multi-part post. Unfortunately RKClient doesn't seem to have simple methods available to handle response mapping like RKObjectManager does... unless I am missing something (which I hope and am and you all will point out for me ;).

Well, this post was similar (but non-functional) and it gave me some ideas of a new technique of using this method on RKObjectLoader
- (RKObjectLoader *)postObject:(id<NSObject>)object delegate:(id<RKObjectLoaderDelegate>)delegate block:(void ( ^ ) ( RKObjectLoader *))block
So now I could get the benefit of mapping that wasn't obvious how to get using RKClient.
Router setup:
RKObjectManager *objectManager = [RKObjectManager objectManagerWithBaseURL:kApiUrlBase];
[objectManager.router routeClass:[PAPetPhoto class] toResourcePath:#"/pet/uploadPhoto" forMethod:RKRequestMethodPOST];
Mapping setup:
RKObjectMapping *papetPhotoMapping = [RKObjectMapping mappingForClass:[PAPetPhoto class]];
[papetPhotoMapping mapKeyPath:#"id" toAttribute:#"identifier"];
[papetPhotoMapping mapAttributes:#"accountId", #"petId", #"photoId", #"filename", #"contentType", nil];
[objectManager.mappingProvider addObjectMapping:papetPhotoMapping];
[objectManager.mappingProvider setSerializationMapping:[papetPhotoMapping inverseMapping] forClass:[PAPetPhoto class]];
[objectManager.mappingProvider setMapping:papetPhotoMapping forKeyPath:#"petPhoto"];
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).
PAPetPhoto *photo = [[PAPetPhoto alloc] init];
[[RKObjectManager sharedManager] postObject:photo delegate:self block:^(RKObjectLoader *loader){
RKParams* params = [RKParams params];
[params setValue:pet.accountId forParam:#"accountId"];
[params setValue:pet.identifier forParam:#"petId"];
[params setValue:_photoId forParam:#"photoId"];
[params setValue:_isThumb ? #"THUMB" : #"FULL" forParam:#"photoSize"];
[params setData:data MIMEType:#"image/png" forParam:#"image"];
loader.params = params;
}];
Server endpoint (Java, Spring MVC)
#RequestMapping(value = "/uploadPhoto", method = RequestMethod.POST)
#ResponseBody
public Map<String, Object> handleFormUpload(#RequestParam("accountId") String accountId,
#RequestParam("petId") String petId,
#RequestParam("photoId") String photoId,
#RequestParam("photoSize") PhotoSizeEnum photoSize,
#RequestParam("image") Part image) throws IOException {
if (log.isTraceEnabled())
log.trace("uploadPhoto. accountId=" + accountId + " petId=" + petId + " photoId=" + photoId + " photoSize=" + photoSize);
PetPhoto petPhoto = petDao.savePetPhoto(accountId, petId, photoId, photoSize, image);
Map<String, Object> map = GsonUtils.wrapWithKeypath(petPhoto, "petPhoto");
return map;
}
Server response JSON (note the keyPath of "petPhoto" that corresponds to the mapping setup):
{
petPhoto = {
accountId = 4ebee3469ae2d8adf983c561;
contentType = "image/png";
filename = "4ebee3469ae2d8adf983c561_4ec0983d036463d900841f09_3FED4959-1042-4D8B-91A8-76AA873851A3";
id = 4ee2e80203646ecd096d5201;
petId = 4ec0983d036463d900841f09;
photoId = "3FED4959-1042-4D8B-91A8-76AA873851A3";
};
}
Delegate:
- (void) objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object {
if ([objectLoader wasSentToResourcePath:#"/pet/uploadPhoto"]) {
PAPetPhoto *photo = (PAPetPhoto*)object;
}
}

Related

How to do in Restkit a PUT request with no body, url params, and get back an object

Lets say that I have to do this dynamic PUT request:
"http://mydomain.com/api/5?value=66"
The body is empty.
I will get in return a 201 (Created) status, and in the body I'm getting back a json object,
Let's call it MyObject that has fields NSNumber* Id, NSString* name;
Now in restkit I have these options:
- [[RKObjectManager sharedManager] putObject:nil mapResponseWith:MyMapping delegate:self];
MyMapping maps MyObject.
The problem is that if I'm sending nil, it doesn't know the mapping and throws "Unable to find a routable path for object of type '(null)' for HTTP Method 'PUT'"
- [[RKClient sharedClient] put:putUrl params:nil delegate:self];
where putUrl = "http://mydomain.com/api/5?value=66"
The problem here is that there is no mapping for the response so only didLoadResponse is called back and didLoadObjects never called
[objectManager.router routeClass:[MyObject class] toResourcePath:putUrl forMethod:RKRequestMethodPUT];
MyObject *obj = [[MyObject alloc] init];
[[RKObjectManager sharedManager] putObject:obj mapResponseWith:MyMapping delegate:self];
The problem here is that first that I fake it (send MyObject as param while it isn't) and it works only for the first time. for the second time I'm trying to use this method I'm getting this exception: "A route has already been registered for class 'MyObject' and HTTP method 'PUT'"
Any suggestion what to do?
Thanks
If anyone is intersted I found the answer after seeing what restkit is doing.
putUrl = "http://mydomain.com/api/5?value=66";
MyMapping maps the returned MyObject that has fields NSNumber* Id, NSString* name;
Here is the code to get it working:
void (^blockLoader)(RKObjectLoader *);
blockLoader = ^(RKObjectLoader *loader) {
loader.delegate = self;
loader.objectMapping = MyMapping;
};
NSString *resourcePath = putUrl;
[[RKObjectManager sharedManager] sendObject:nil toResourcePath:resourcePath usingBlock:^(RKObjectLoader *loader) {
loader.method = RKRequestMethodPUT;
blockLoader(loader);
}];

RestKit: how to map URL param to object attribute

I've got REST service method like this one
/GetOfficeDocument?officeId=259
which returns an array of documents. Document in the app is a NSManagedObject object that has relationship to an office. How can I map officeId param to office relationship of my Document?
I know I should override objectLoader:willMapData:, but I don't know what exactly should I do inside of this method. The documentation is useless.
UPD. The response of the server looks like this:
[{"AddedDate":"\/Date(1261484400000+0400)\/","Title":"Some text","Uri":"\/Document\/News\/851"}]
As you see, officeId is not contained in response, only in URL. I can extract it in objectLoader:willMapData: using
[[[loader URL] queryParameters] objectForKey:#"officeId"]
but where should I put it next? Mappable data parameter is a mutable array, what should I place there? No idea.
You could try to inject the OfficeId value in each document item returned in the response like so:
- (void)objectLoader:(RKObjectLoader *)loader willMapData:(inout __autoreleasing id *)mappableData
{
NSString *officeId = [[[loader URL] queryParameters] objectForKey:#"officeId"];
NSMutableArray *newMappableData = [[NSMutableArray alloc] initWithCapacity:[*mappableData count]];
for (NSDictionary *documentDict in *mappableData)
{
NSMutableDictionary = newDocumentDict = [documentDict mutableCopy];
[newDocumentDict setObject:officeId forKey:#"OfficeId"];
[newMappableData addObject:newDocumentDict];
}
*mappableData = newMappableData;
}
And use something similar to the following in your Document mapping:
[documentMapping mapAttributes:#"AddedDate", #"Title", #"Uri", #"OfficeId", nil];
[documentMapping mapKeyPath:#"" toRelationship:#"office" withMapping:officeMapping];
[documentMapping connectRelationship:#"office" withObjectForPrimaryKeyAttribute:#"OfficeId"];
I usually add the RKObjectMapping to the managedObject class
Add this to your Document.h
+ (RKObjectMapping *)objectMapping;
Add this method to your Document.m
+ (RKObjectMapping *)objectMapping {
RKManagedObjectMapping *mapping = [RKManagedObjectMapping mappingForClass:[self class] inManagedObjectStore:[[RKObjectManager sharedManager] objectStore]];
mapping.primaryKeyAttribute = #"word";
[mapping mapKeyPath:#"word" toAttribute:#"word"];
[mapping mapKeyPath:#"min_lesson" toAttribute:#"minLesson"];
}
Off course you should change the key paths to your Document object properties. each pair is the name of the key on the server responds and it's corresponded keyPath on your managedObject.
Then when you initialize the objectManager you can set the mapping for each managedObject you have.
RKManagedObjectStore *store = [RKManagedObjectStore objectStoreWithStoreFilename:databaseName usingSeedDatabaseName:seedDatabaseName managedObjectModel:nil delegate:self];
objectManager.objectStore = store;
//set the mapping object from your Document class
[objectManager.mappingProvider setMapping:[SRLetter objectMapping] forKeyPath:#"Document"];
YOu can find a great tutorial here - RestKit tutorial. In the middle of the article you will find data about mapping.

Restkit, sending post data with loadObjectsAtResourcePath

If i am making a request with restkit i can use the shared client to send post parameters.
How can i do the same with shared Object manager, there seems to be no function to post data when objects are requested.
To re-iterate, am looking to send some post data when i am using loadObjectsAtResourcePath
Thanks
Must you use loadObjectsAtResourcePath? Here's what I use to send POST requests to my server
RKParams* params = [RKParams params];
[params setValue:#"The text" forParam:#"text"];
RKClient* myClient = [RKClient sharedClient];
[myClient post:resourceURL params:params delegate:self];
And you get your response back with
- (void)request:(RKRequest *)request didLoadResponse:(RKResponse *)response
PS: Just found this link: https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON
You can use the block style object loader to customize the request:
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:#"/monkeys.json" usingBlock:^(RKObjectLoader* loader) {
loader.objectMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[Monkey class]];
loader.method = RKRequestMethodPOST;
}];
https://github.com/RestKit/RestKit/blob/master/Code/ObjectMapping/RKObjectManager.h#L374

Mapping a JSON response to an object using RestKit and Objective-C

I am relatively new to Objective-C and am attempting to use RestKit to receive a JSON response from a web service. I have successfully received the data back to my application, which looks like this viewing the response:
{id:"1","Translation":"Test"}
I would like to map this translation to my "Translation" object in my application, but have tried a few different ways but am not sure how to achieve this.
So my questions are:
How can I map this response to my Translation object
Am I doing this correctly, creating a method to complete this call outwit my view controller?
My Translation Object
#implementation Translation
#synthesize identifier = _identifier;
#synthesize translation = _translation;
- (NSDictionary*)elementToPropertyMappings {
return [NSDictionary dictionaryWithKeysAndObjects:
#"id", #"identifier",
#"translation", #"translation",
nil];
}
#end
My Translate Method
- (NSString *)performTranslation:(NSString *)translation
{
NSString *data = [[NSString alloc] initWithFormat:#"{\"SourceId\": \"%#\",\"RegionTag\": \"%#\",\"InputString\": \"%#\"}", #"1", #"Glasgow", translation];
NSString *post = data;
RKRequest *MyRequest = [[RKRequest alloc] initWithURL:[[NSURL alloc] initWithString:#"http://my.url.com/Translation/Translate"]];
MyRequest.method = RKRequestMethodPOST;
MyRequest.HTTPBodyString = post;
MyRequest.additionalHTTPHeaders = [[NSDictionary alloc] initWithObjectsAndKeys:#"application/json", #"Content-Type", #"application/json", #"Accept", nil];
[MyRequest send];
RKResponse *Response = [MyRequest sendSynchronously];
return Response.bodyAsString; <--- looking to map this to translation object here
}
The snippet of your code seems a bit outdated. I strongly recommend reading the newest Object Mapping guide in order to leverage RestKit into it's fullest potential - especially the part Mapping without KVC.
Edit:
In order to post an object with RestKit and receive back an answer, we define a TranslationRequest class that will hold our request & Translation to hold our response.
Firstly, we set up our RKObjectManager and mappings (i usually do this in my AppDelegate):
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kOurBaseUrl];
[manager setSerializationMIMEType:RKMIMETypeJSON];
//this is a singleton, but we keep the manager variable to avoid using [RKObjectManager sharedManager] all the time
//Here we define a mapping for the request. Note: We define it as a mapping from JSON to entity and use inverseMapping selector later.
RKObjectMapping *translationRequestMapping = [RKObjectMapping mappingForClass:[TranslationRequest class]];
[translationRequestMapping mapKeyPath:#"RegionTag" toAttribute:#"regionTag"];
...
[[manager mappingProvider] setSerializationMapping:[translationRequestMapping inverseMapping] forClass:[TranslationRequest class]];
//now we define the mapping for our response object
RKObjectMapping *translationMapping = [RKObjectMapping mappingForClass:[Translation class]];
[translationMapping mapKeyPath:#"id" toAttribute:#"identifier"];
[translationMapping mapKeyPath:#"Translation" toAttribute:#"translation"];
[[manager mappingProvider] addObjectMapping:mapping];
//finally, we route our TranslationRequest class to a given endpoint
[[manager router] routeClass:[TranslationRequest class] toResourcePath:kMyPostEndpoint];
This should be enough of the necessary setup. We can call our backend anywhere in the code (e.g. in any controller) like this:
//we create new TranslationRequest
TranslationRequest *request = [[TranslationRequest alloc] init];
[request setRegionTag:#"Hello"];
....
//then we fetch the desired mapping to map our response with
RKObjectMapping *responseMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:class]
//and just call it. Be sure to let 'self' implement the required RKObjectManagerDelegate protocol
[[RKObjectManager sharedManager] postObject:request mapResponseWith:responseMapping delegate:self];]
Try this approach and let me know if you need any assistance.. I was not able to test it fully as i don't have any suitable backend that will return the responses, but judging from the RestKit log this should work.
You need to pass the returned JSON string into a JSON parser. I use SBJSON. You can then use the resulting dictionary to populate the properties of your object.
RestKit seems to have native objects that encapsulate four different JSON parsers. However, I'd advise caution because they seem to assume that the top level parsed object will always be a dictionary.
As another aside, the example in your question is not valid JSON. It should look like this:
{"id":"1","Translation":"Test"}

RestKit: How does one post an array of objects?

Question summary:
Consider a class SyncObject that is KVC-compliant with properties such as: time, someValue, lastChange, uuid.
Consider an NSArray containing exclusively instances of SyncObject.
I need to submit the array to the server as a JSON array.
How would one submit this array to the server using HTTP POST using RestKit?
Example array:
[
{
"time": "14:45 10/21/2011",
"someValue": "15",
"lastChange": "14:45 10/21/2011",
"uuid": "0b07c510-f4c8-11e0-be50-0800200c9a66"
},
{
"time": "14:50 10/21/2011",
"someValue": "62",
"lastChange": "14:51 10/21/2011",
"uuid": "1a6d4480-f4c8-11e0-be50-0800200c9a66"
}
]
Details
I have an array of objects that I need to the server as JSON. It seems to me that RestKit is the easiest way to do this: I'm trying to avoid converting objects into a set of NSDictionary objects, and then using some JSON encoder to get JSON which I can POST to the server.
So, having created the array, and having set up the mapping for the class of objects stored in the array, I naturally try to POST to the server.
RKObjectManager* mgr = [RKObjectManager objectManagerWithBaseURL:#"http://localhost/someweb/api/"];
mgr.serializationMIMEType = RKMIMETypeFormURLEncoded;
mgr.client.username = #"username";
mgr.client.password = #"password";
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
[mapping mapKeyPath: #"time" toAttribute:#"time" ];
[mapping mapKeyPath: #"someValue" toAttribute:#"someValue" ];
[mapping mapKeyPath: #"lastChange" toAttribute:#"lastChange" ];
[mapping mapKeyPath: #"uuid" toAttribute:#"uuid" ];
RKObjectMapping* mappingForSerialization = [mapping inverseMapping];
[mgr.mappingProvider setSerializationMapping:mappingForSerialization
forClass:[NSManagedObject class]];
[mgr.router routeClass:[NSManagedObject class] toResourcePath:#"/sync" forMethod:RKRequestMethodPOST];
[mgr postObject:array delegate:nil/*self*/];
However, this is what I get out:
2011-10-11 14:57:51.769 AppConnect[1974:6e0b] *** Terminating app due to uncaught exception '(null)', reason: 'Unable to find a routable path for object of type '__NSArrayI' for HTTP Method 'POST''
Apparently, RestKit does not know how to handle NSArrays.
How does one post an array of objects using RestKit?
I've tried something different: I replaced the last line with a manual send through RKObjectLoader.
//[mgr postObject:[NSMutableDictionary dictionaryWithObject:array forKey:#"data"] delegate:nil/*self*/];
NSString* syncPath = #"/sync";
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];
//objectLoader.managedObjectStore = mgr.objectStore;
objectLoader.params = [NSDictionary dictionaryWithObject:array
forKey:#"MyData"];
[objectLoader send];
Unfortunately, this does not apply mapping of any sort, and instead transmits an array of objects' descriptions. Setting serializationMIMEType also does not affect the structure of transmitted contents, and params are always transmitted as application/x-www-form-urlencoded.
I also tried assigning serialization mapping and passing the object as targetObject and sourceObject (this seems to be what RestKit does internally in -[RKObjectManager postObject:delegate:]).
RKObjectLoader * objectLoader = [mgr objectLoaderWithResourcePath:syncPath delegate:self];
objectLoader.method = RKRequestMethodPOST;
//objectLoader.objectClass = [NSManagedObject class];
//objectLoader.managedObjectStore = mgr.objectStore;
objectLoader.params = [NSMutableDictionary dictionaryWithObject:array
forKey:#"MyData"];
objectLoader.serializationMapping = mapping;
objectLoader.serializationMIMEType = RKMIMETypeJSON;
objectLoader.sourceObject = objectLoader.params;
objectLoader.targetObject = objectLoader.params;
[objectLoader send];
Unfortunately, no mapping occurs this way:
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.network:RKObjectLoader.m:290 POST or PUT request for source object {
MyData = (
"<NSManagedObject: 0x5935430> (entity: SomeRecord; id: 0x5934da0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p1> ; data: <fault>)",
"<NSManagedObject: 0x5935730> (entity: SomeRecord; id: 0x5934db0 <x-coredata://64DF9977-DA50-4FCD-8C20-4132E58439BF/SomeRecord/p2> ; data: <fault>)"
);
}, serializing to MIME Type application/json for transport...
2011-10-12 12:36:48.143 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:428 Starting mapping operation...
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'time'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'someValue'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'lastChange'
2011-10-12 12:36:48.145 MyProject[5119:207] T restkit.object_mapping:RKObjectMappingOperation.m:291 Did not find mappable attribute value keyPath 'uuid'
2011-10-12 12:36:48.145 MyProject[5119:207] D restkit.object_mapping:RKObjectMappingOperation.m:448 Mapping operation did not find any mappable content
2011-10-12 12:36:48.146 MyProject[5119:207] T restkit.network:RKRequest.m:211 Prepared POST URLRequest '<NSMutableURLRequest http://someurl/api/sync?request=provide_key>'. HTTP Headers: {
Accept = "application/json";
"Content-Length" = 0;
}. HTTP Body: .
The restkit does not fund routable path for NSArray, because you defined your routing for NSManagedObject class. You probably want to create a custom class, say MySyncEntity that holds the ivars you define in your mapping. Then, you create your mapping like this:
RKObjectMapping* mapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
....
[myManager setSerializationMIMEType:RKMIMETypeJSON];
[[myManager router] routeClass:[MySyncEntity class] toResourcePath:#"/sync"];
then you should be able to post your object to the API backend as JSON object.
Further clarification:
In this case, we want to post an array of NSManagedObject instances into a JSON based API. To do that we need to create a sync entity, that holds the objects in an array:
#interface MySyncEntity : NSObject {}
#property (nonatomic, retain) NSArray* mySyncArray;
...
#end
The mySyncArray will hold the payload we'd like to submit to the rest backend. Then, we create appropriate mapping for both NSManagedObject that will be sent in mySyncArray and the MySyncEntity entity itself.
RKObjectManager *manager = [RKObjectManager objectManagerWithBaseURL:kBaseUrl];
...
RKObjectMapping *mngObjMapping = [RKObjectMapping mappingForClass:[NSManagedObject class]];
[mngObjMapping mapKeyPath: #"time" toAttribute:#"time"];
[mngObjMapping mapKeyPath: #"recordLevel" toAttribute:#"recordLevel"];
.... //map as many properties as you wish
[[manager mappingProvider] setSerializationMapping:[mngObjMapping inverseMapping]
forClass:[NSManagedObject class]];
//now, we create mapping for the MySyncEntity
RKObjectMapping *syncEntityMapping = [RKObjectMapping mappingForClass:[MySyncEntity class]];
[syncEntityMapping mapKeyPath:#"mySyncArray" toRelationship:#"mySyncArray" withMapping:mngObjMapping];
[[manager mappingProvider] setSerializationMapping:[syncEntityMapping inverseMapping]
forClass:[MySyncEntity class]];
Now with the mappings defined we can post the object to the server
[manager postObject:mySyncInstance delegate:nil];
The contents of mySyncInstance array will be mapped according to mngObjMapping and sent to defined rest endpoint.
As a further clarification, I'd like to point out that in mja's answer the key thing is
[syncEntityMapping mapKeyPath:#"mySyncArray" toRelationship:#"mySyncArray" withMapping:mngObjMapping];
This says "the mySyncArray keypath is an array which contains objects that should be mapped according to mngObjMapping".