Wresting a simple dictionary from RestKit - ios

I am attempting to upgrade my current RestKit to 0.20.3, and in one case I need to get the result back as a dictionary, not mapped to any object.
Unfortunately, the code below results in an essentially empty RKMappingResult object, despite the fact that a correct dictionary does exist deeper in RestKit (I checked).
[self.objectManager addResponseDescriptor:[RKResponseDescriptor responseDescriptorWithMapping:[RKObjectMapping mappingForClass:[NSMutableDictionary class]]
method:RKRequestMethodGET
pathPattern:#"permission.json"
keyPath:nil
statusCodes:nil]];
[self loadObject:[[NSMutableDictionary alloc] init]
method:RKRequestMethodGET
path:#"permission.json"
params:nil
success:^(RKObjectRequestOperation *op, RKMappingResult *result) {
if (success)
success([result dictionary]);
}
failure:^(RKObjectRequestOperation *op, NSError *error) {
if (failure)
failure(error);
}];
Load object calls the following:
RKObjectRequestOperation *const operation =
[self operationForObject:object
method:method
path:path
params:params
success:success
failure:failure];
[self.objectManager enqueueObjectRequestOperation:operation];
return operation;
Can anyone give me some direction on how I might convince RestKit to give me back a dictionary?

This is indeed one of the correct ways to create the mapping instance for a dictionary result:
[RKObjectMapping mappingForClass:[NSMutableDictionary class]]
But you still need to set the key names that should be mapped or RestKit will just do no mapping.

Related

How to Get Object based response in Restkit 0.20.3

Hi have used restkit in my several previous projects with version 0.10.0. But now i am going to move with new restkit v0.20.3.
I followed all the steps from upgrading 10.0 to 20.0 from HERE.
I am able execute my request and response also came under success blog. But i can get the property of my response object. That is very shocking for now. I can get value only by [data valueForKey:#""] which is not good i guess in restkit.
Can any one tell me about how we get value from object's property.
[operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"%lu", (unsigned long)mappingResult.array.count);
DataForResponse *data = [mappingResult.array objectAtIndex:0];
User *user = [data valueForKey:#"user"];
User *user = [[data.user allObjects] firstObject];
NSLog(#"%#",[user valueForKey:#"email"]);
RKLogInfo(#"Load collection of Users: %#", mappingResult.array);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"%#",operation.HTTPRequestOperation.responseString);
RKLogError(#"Operation failed with error: %#", error);
}];
My goal is to get value of email like from user.email
After searching & based on my restkit knowledge below code is worked.
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[DataForResponse objectMappingForDataResponse:LOGIN] method:RKRequestMethodPOST pathPattern:nil keyPath:#"data" statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
[rkomForLogin addResponseDescriptor:responseDescriptor];
RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:#[ responseDescriptor ]];
operation.targetObject = data;
[rkomForLogin postObject:nil path:#"login" parameters:dict success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
// Handled with articleDescriptor
NSLog(#"%#",operation.HTTPRequestOperation.responseString);
DataForResponse *data = [mappingResult.array objectAtIndex:0];
User *user = [[data.user allObjects] firstObject];
NSLog(#"%#",[user email]);
NSLog(#"%ld",operation.HTTPRequestOperation.response.statusCode);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
// Transport error or server error handled by errorDescriptor
NSLog(#"%#",operation.HTTPRequestOperation.responseString);
RKLogError(#"Operation failed with error: %#", error);
}];
This is same object based response that i was getting in restkit 0.10 so this is way to execute a request.

Restkit Add custom values when mapping

Restkit mapping and inserting data works fine, but I need to add custom values to the database (not from JSON)
RKEntityMapping *entityMapping = [RKEntityMapping mappingForEntityForName:entityName inManagedObjectStore:managedObjectStore];
[entityMapping addAttributeMappingsFromDictionary:dict];
if (uniqKey != nil) {
entityMapping.identificationAttributes = #[ uniqKey ];
}
// Set MIME Type to JSON
manager.requestSerializationMIMEType = RKMIMETypeJSON;
// register mappings with the provider using a response descriptor
RKResponseDescriptor *responseDescriptor =
[RKResponseDescriptor responseDescriptorWithMapping:entityMapping
method:RKRequestMethodPOST
pathPattern:path
keyPath:rootKeyPath
statusCodes:[NSIndexSet indexSetWithIndex:200]];
[manager addResponseDescriptor:responseDescriptor];
[manager postObject:nil path:path parameters:queryParams success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
if (mappingResult.array.count != 0) {
NSDictionary *data = mappingResult.array[0];
NSLog(#"data: %#", data);
}else{
NSLog(#"Unable to fetch data from: %#", path);
}
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error response': %#", error);
}];
Other than NSPredict and filtering the data, is is possible to insert values (like string) manually while mapping?
You can modify the objects from the mapping result in the completion block, but then you need to explicitly save the context and other observers of the context will have received a save notification. This is the super simple approach.
Alternatively you could override willSave or use NSManagedObjectContextWillSaveNotification (the latter being the better option) to trigger your custom logic. Your changes would then be made inline with the RestKit changes and would be automatically saved.
Solved the issue using
[[mappingResult set] setValue:value forKey:key];
in manager on success block.

How to save to Core Data RKMappingResult object in RestKit?

I try to save to Core Data NSManagedObject which I got from server. But I don't know any idea how to save object got from [mappingResult firstObject] in success block to Core Data. How can I do this? Should I use RKObjectManager's postObject or RKManagedRequestOperation? Should I do [managedObjectContext insertNewObjectForEntityForName:#""] before this?I can't find any instructions in official docs for this case and need some help.
**EDIT: **I initialise RKManagedRequestOperation like this:
RKResponseDescriptor* responseDescriptor =[RKResponseDescriptor
responseDescriptorWithMapping:[UserMapping mappingForUser]
method:RKRequestMethodPOST
pathPattern:kUserEndpoint
keyPath:#"profile"
statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)];
RKRequestDescriptor* requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[UserMapping mappingForUserProfileModel]
objectClass:[User class] rootKeyPath:#"profile" method:RKRequestMethodPOST];
[[RKObjectManager sharedManager] addRequestDescriptor:requestDescriptor];
[[RKObjectManager sharedManager] addResponseDescriptor:responseDescriptor];
userObject = [User new];
NSDictionary* userParameters = #{ #"user_id" : [User sharedUser].userId};
[[RKObjectManager sharedManager] appropriateObjectRequestOperationWithObject:resumeObject method:RKRequestMethodPOST
path:kUserEndpoint
parameters:userParameters];
RKManagedObjectRequestOperation* managedRequest = [[RKManagedObjectRequestOperation alloc]
initWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#%#", kService, kUserEndpoint]]]
responseDescriptors:#[responseDescriptor]];
managedRequest.managedObjectContext = _managedObjectContext;
[managedRequest setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"MAPPING = %#", [mappingResult firstObject]);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
}];
[[RKObjectManager sharedManager] enqueueObjectRequestOperation:managedRequest];
EDIT2: RestKit doesn't save mapped data to CoreData. But userObject.title saves perfectly:
userObject = [_managedObjectContext insertNewObjectForEntityForName:#"User"];
userObject.title = #"USER_NAME";
NSDictionary* userParameters = #{ #"user_id" : [User sharedUser].userId};
[[RKObjectManager sharedManager] postObject:userObject path:kUserEndpoint parameters:userParameters
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
} failure:^(RKObjectRequestOperation *operation, NSError *error) { }];
You need to take a step back as your suggestions are shooting in the dark.
If you configure your object manager with a managed object store and create response descriptors with entity mappings then when you receive data as a result of requests this will be converted into managed objects. These objects will automatically be saved to the core data store before the success block is called.
Any other objects you want to create can be created as usual and you need to explicitly save the context.
Sending requests with RestKit doesn't itself change the store contents, only the response results in changes.
See this tutorial. There is an example of using RestKit with object management and Code Data
https://github.com/alexanderedge/RestKitTutorial1

RESTKit POST Request Tutorial

I would like to know if there is a specific tutorial on how to do a POST request with RESTKit. I have looked at some tutorials but I haven't found any that say, "This is exactly how you do a POST request with RESTKit." Help is much appreciated.
Assuming you already have a mapped model, you can simply perform this:
First, set a requestDescriptor with the inverseMapping of your responseDescriptor, assuming you have one with your mapping.
//This is used for mapping responses, you already should have one of this. PS:[Data mapping] is a method that returns an RKObjectMapping for my model. You should create yours or use a previous created one
RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:[Data mapping] pathPattern:nil keyPath:#"data" statusCodes:statusCodeSet];
[[RKObjectManager sharedInstance] addResponseDescriptor:responseDescriptor];
//Inverse mapping, to perform a POST
RKRequestDescriptor *requestDescriptor = [RKRequestDescriptor requestDescriptorWithMapping:[[Data mapping] inverseMapping] objectClass:[Data class] rootKeyPath:nil];
[[RKObjectManager sharedInstance] addRequestDescriptor:requestDescriptor];
After that, to perform a POST, just simply call the method below. Restkit will get the instance that you are trying to post, serialize it and send to the path chosen.
[[RKObjectManager sharedInstance] postObject:instanceOfYourModel path:yourPathHere parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"Success");
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Error");
}];
If you don't have a mapped model, let me know so we can try something else.

RestKit 0.20 Ignore putObject: mapping

I'm trying to send an object to the server (PUT request) without a mapping because I already have everything I need from the server. The callback directly goes to failure, even though the server has sucessfully created the object.
Here is an example of what I am doing:
- (void) PUTsuccess:(void (^)(RKObjectRequestOperation *operation, RKMappingResult *mappingResult))success
failure:(void (^)(RKObjectRequestOperation *operation, NSError *error))failure
{
RKObjectManager *objectManager = [YSManager objectManager];
[objectManager putObject:self path:[kPutPath stringByAppendingString:self.id] parameters:kAPIDefaultParameters success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
NSLog(#"operation.HTTPRequestOperation.request.HTTPBody: %#", [[NSString alloc] initWithData:operation.HTTPRequestOperation.request.HTTPBody encoding:NSUTF8StringEncoding]);
if (success) {
success(operation, mappingResult);
}
}
failure:^(RKObjectRequestOperation *operation, NSError *error) {
NSLog(#"Failure! Error: %#", error.localizedDescription);
if (failure) {
failure(operation, error);
}
}];
}
The server response is 201 created and I can find back my object in the server so that's all good, but still, the callback directly fires failure because it's trying to map my object, the error in the failure callback is:
Error: No response descriptors match the response loaded.
Thanks a lot, any suggestion will be appreciated!
Update 1
Added dictionary mapping now:
RKObjectMapping *idMapping = [RKObjectMapping requestMapping];
[idMapping addAttributeMappingsFromArray:#[]];
RKResponseDescriptor *responseDescriptorID = [RKResponseDescriptor responseDescriptorWithMapping:idMapping
pathPattern:[kRequestPath stringByAppendingString:#":code"]
keyPath:#"objects"
statusCodes:statusCodes];
Define a response descriptor simply to map the response (or part of it) to an NSDictionary.

Resources