Send post request and map response to object

2.6k Views Asked by At

I am new to restKit and I have a few questions for you. I cant understand how to send Post request using json/xml to my web services and map the incoming reply with my classes. Can any one give me a help on that. The code I am using is this: in my applicationDelegate I am instantiating the RKObjectManager providing the base URL:

RKObjectManager* manager = [RKObjectManager objectManagerWithBaseURL:@"https://example.com/services/"]; 

   // Request params in Dictionary 
    NSArray *objects = [NSArray arrayWithObjects: email, password, 
nil]; 
    NSArray *keys = [NSArray arrayWithObjects:@"username", 
@"password", nil]; 
    NSDictionary *params = [NSDictionary dictionaryWithObjects:objects 
forKeys:keys]; 
    NSLog(@"Manager: %@", [RKObjectManager 
sharedManager].description); 
    // User object Mapping 
    RKObjectMapping* userMapping = [RKObjectMapping mappingForClass: 
[User class]]; 
    [userMapping mapKeyPath:@"userName" toAttribute:@"userName"]; 
    [userMapping mapKeyPath:@"lastName" toAttribute:@"lastName"]; 
    [userMapping mapKeyPath:@"active" toAttribute:@"active"]; 
    [[RKObjectManager sharedManager].mappingProvider 
setMapping:userMapping forKeyPath:@"user"]; 
    [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/ 
login" delegate:self]; 

When a post is send to /login the server should send back a valid json and then map that json to my User class.

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObjects: 
(NSArray*)objects { 
    RKLogInfo(@"Load collection of Articles: %@", objects); 
} 

- (void)objectLoader:(RKObjectLoader*)objectLoader didFailWithError: 
(NSError *)error 
{ 
    NSLog(@"Objecy Loader failed: %@", error); 
} 

- (void)request:(RKRequest *)request didFailLoadWithError:(NSError 
*)error 
{ 
    NSLog(@"Request failed"); 
} 

- (void)request:(RKRequest*)request didLoadResponse: 
(RKResponse*)response { 
    if ([request isGET]) { 
        // Handling GET /foo.xml 
        if ([response isOK]) { 
            // Success! Let's take a look at the data 
            NSLog(@"Retrieved XML: %@", [response bodyAsString]); 
        } 
    } else if ([request isPOST]) { 
        // Handling POST /other.json 
        if ([response isXML]) { 
         ///NSLog(@"Seng a JSON request:! \n %@", [request 
HTTPBodyString]); 
            NSLog(@"Got a responce! \n %@", [response bodyAsString]); 
        } 
    } else if ([request isDELETE]) { 
        // Handling DELETE /missing_resource.txt 
        if ([response isNotFound]) { 
            NSLog(@"The resource path '%@' was not found.", [request 
resourcePath]); 
        } 
    } 
} 

When I execute it the objectLoader method are not triggered, my understanding of restkit is that they should get called when

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/login" 
delegate:self];

is executed ? Any help is appreciated :)

2

There are 2 best solutions below

1
On

did you remember to set the delegate for restkit to that user class (or where ever you have the delegates being caught) with

@interface User : NSObject<RKObjectLoaderDelegate>{
}

you probably did but its worth mentioning incase :P

and the self that gets passed in this line is that class?

[[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/ 
login" delegate:self]; 

also i think the newer way to add the mapping is and set up for posts is

[sharedManager.mappingProvider addObjectMapping:userMapping];
[sharedManager.mappingProvider setMapping:userMapping forKeyPath:@"/somepath"];

[sharedManager.mappingProvider setSerializationMapping:[userMapping inverseMapping] forClass:[User class]];
 // Must set the router up to handle posts
 [sharedManager.router routeClass:[User class] toResourcePath:@"/api/users" forMethod:RKRequestMethodPOST];

edit again : and create a post using the loader like this. probably all over kill for what your doing but cant hurt to have a look

RKObjectLoader* loader = [RKObjectLoader loaderWithResourcePath:url objectManager:self.objectManager delegate:self.currentDelegate];
    loader.method = RKRequestMethodPOST;
    loader.sourceObject = self;
    loader.targetObject = self;  

    loader.serializationMIMEType = self.objectManager.serializationMIMEType;
    loader.serializationMapping = [self.objectManager.mappingProvider serializationMappingForClass:self.mappingClass];

    loader.objectMapping = [self.objectManager.mappingProvider objectMappingForClass:self.mappingClass];

    [loader send]; //<<the actual post
0
On

Well, you do not even send your data to the server. A couple of days ago, I wrote a snippet explaining how to post a NSDictionary (as JSON) to a server using RestKit.