Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Restkit to POST JSON and map response

I'm using RestKit for the first time, and its feature-set looks great. I've read the document multiple times now and I'm struggling to find a way to POST JSON params to a feed and map the JSON response. From searching on stackoverflow I found a way to send the JSON params via a GET, but my server only takes POST.

Here is the code I have so far:

RKObjectMapping *issueMapping = [RKObjectMapping mappingForClass:[CDIssue class]];
[objectMapping mapKeyPath:@"issue_id" toAttribute:@"issueId"];
[objectMapping mapKeyPath:@"title" toAttribute:@"issueTitle"];
[objectMapping mapKeyPath:@"description" toAttribute:@"issueDescription"];
RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@"http://restkit.org"];
RKManagedObjectStore* objectStore = [RKManagedObjectStore objectStoreWithStoreFilename:@"News.sqlite"];
objectManager.objectStore = objectStore;

NSDictionary params = [NSDictionary dictionaryWithObjectsAndKeys: @"myUsername", @"username", @"myPassword", @"password", nil];
NSURL *someURL = [objectManager.client URLForResourcePath:@"/feed/getIssues.json" queryParams:params];

[manager loadObjectsAtResourcePath:[someURL absoluteString] objectMapping:objectMapping delegate:self]

From the another stackoverflow thread (http://stackoverflow.com/questions/9102262/do-a-simple-json-post-using-restkit), I know how to do a simple POST request with the following code:

RKClient *myClient = [RKClient sharedClient];
NSMutableDictionary *rpcData = [[NSMutableDictionary alloc] init ];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];

//User and password params
[params setObject:password forKey:@"password"];
[params setObject:username forKey:@"email"];

//The server ask me for this format, so I set it here:
[rpcData setObject:@"2.0" forKey:@"jsonrpc"];
[rpcData setObject:@"authenticate" forKey:@"method"];
[rpcData setObject:@"" forKey:@"id"];
[rpcData setObject:params forKey:@"params"];

//Parsing rpcData to JSON! 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:rpcData error:&error];    

//If no error we send the post, voila!
if (!error){
    [[myClient post:@"/" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self] send];
}

I was hoping someone would help me marry these two code snippets into a workable solution.

like image 908
elprl Avatar asked Nov 14 '22 10:11

elprl


1 Answers

To post an object what I do is associate a path to an object. Then use the method postObject from RKObjectManager.

I asume that you have already configured RestKit so you have the base path set and defined the object mapping for your CDIssue as you have in the code that you already have. With that in mind try this code:

//We tell RestKit to asociate a path with our CDIssue class
RKObjectRouter *router = [[RKObjectRouter alloc] init];
[router routeClass:[CDIssue class] toResourcePath:@"/path/to/my/cdissue/" forMethod:RKRequestMethodPOST];
[RKObjectManager sharedManager].router = router;

//We get the mapping for the object that you want, in this case CDIssue assuming you already set that in another place
RKObjectMapping *mapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForClass:[CDIssue class]];

//Post the object using the ObjectMapping with blocks
[[RKObjectManager sharedManager] postObject:myEntity usingBlock:^(RKObjectLoader *loader) {

    loader.objectMapping = mapping;
    loader.delegate = self;

    loader.onDidLoadObject = ^(id object) {
        NSLog(@"Got the object mapped");
        //Be Happy and do some stuff here
    };

    loader.onDidFailWithError = ^(NSError * error){
        NSLog(@"Error on request");
    };

    loader.onDidFailLoadWithError = ^(NSError * error){
        NSLog(@"Error on load");
    };

    loader.onDidLoadResponse = ^(RKResponse *response) {
        NSLog(@"Response did arrive");
        if([response statusCode]>299){
            //This is useful when you get an error. You can check what did the server returned
            id parsedResponse = [KFHelper JSONObjectWithData:[response body]];
            NSLog(@"%@",parsedResponse);
        }

    };


}];
like image 190
clopez Avatar answered Nov 16 '22 03:11

clopez