Skip to content

Posting Data Objects

grgcombs edited this page Aug 5, 2011 · 1 revision

Posting Data Objects with RestKit

In a Google Group discussion, Bob Oottinger offered a clean, simple, concise example of posting data objects to a back-end server.

@interface PostMessage_Restkit : NSObject {
    NSString*  _device;
    NSString*  _msgType;
    NSString*  _txtBody;
}

@property (nonatomic, retain) NSString*  device;
@property (nonatomic, retain) NSString*  msgType;
@property (nonatomic, retain) NSString*  txtBody;

+ (void) initMap:(RKObjectManager*)mgr;

@end





@implementation PostMessage_Restkit
                   
@synthesize device             = _device;
@synthesize msgType            = _msgType;
@synthesize txtBody            = _txtBody;

+ (void) initMap:(RKObjectManager*)mgr {
    
    mgr.serializationMIMEType = RKMIMETypeFormURLEncoded;
    
    RKObjectMapping* pmsg = [RKObjectMapping mappingForClass:[NSMutableDictionary class]];
  
    [pmsg mapKeyPath: @"device"             toAttribute:@"device"       ];  
    [pmsg mapKeyPath: @"message_type"       toAttribute:@"msgType"      ];
    [pmsg mapKeyPath: @"txt_body"           toAttribute:@"txtBody"      ];
    
    RKObjectMapping* pmsgSerializeMapping = [pmsg inverseMapping];
  	[mgr.mappingProvider setSerializationMapping:pmsgSerializeMapping forClass:[PostMessage_Restkit class]];
  	
    [mgr.router routeClass:[PostMessage_Restkit class] toResourcePath:@"/messages" forMethod:RKRequestMethodPOST];    
}




- (void) initBackendCommunication {

    //
    // set a bunch of RestKit initializations
    //
    
    gBaseURL = [@"http://test.backend.com" retain];
    RKObjectManager* rkoManager = [RKObjectManager objectManagerWithBaseURL:gBaseURL];
    [PostMessage_Restkit               initMap:rkoManager];
}




-(void) postNewMessage:(NSString *)msg 
{
    //
    // build messages
    //
    PostMessage_Restkit *pmsg = [PostMessage_Restkit alloc];
   
    pmsg.device             = [gDeviceMac retain];
    pmsg.msgType            = @"new_email";
    pmsg.reference          = [[NSNumber numberWithInt:0] retain];;
    pmsg.txtBody            = [msg retain];
    
    [[RKObjectManager sharedManager] postObject:pmsg delegate:self];
        
    return;
}