AddisDev
AddisDev

Reputation: 1801

Objective-C Asynchronous NSURLConnection to Ruby Server

I am having trouble sending asynchronous NSURLRequests to a Ruby server. When I use the following, a connection is never made:

self.data = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:@"http://domain.com/app/create_account.json"]];
[request setHTTPMethod:@"POST"];
[request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request addValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request addValue:@"form-data" forHTTPHeaderField:@"Content-Disposition"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

However, when I exchange the last line with:

NSData *returnData = [NSURLConnection sendSynchronousRequest:request   returningResponse:nil error:nil];

Everything works great. But I do need to make this connection asynchronously...

EDIT-Working Example

NSURL *url = [NSURL URLWithString:@"http://domain.com/app/create_account.json"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:data forKey:@"data"];
[request setDelegate:self];
[request startAsynchronous];

It seems RESTful services need their own third party framework in this case.

Upvotes: 2

Views: 414

Answers (1)

NIKHIL
NIKHIL

Reputation: 2719

you can try following using restkit api

- (void)sendAsJSON:(NSDictionary*)dictionary {

RKClient *client = [RKClient clientWithBaseURL:@"http://restkit.org"];        

// create a JSON string from your NSDictionary 
id<RKParser> parser = [[RKParserRegistry sharedRegistry] parserForMIMEType:RKMIMETypeJSON];
NSError *error = nil;
NSString *json = [parser stringFromObject:dictionary error:&error];

// send your data
if (!error)
     [[RKClient sharedClient] post:@"/some/path" params:[RKRequestSerialization serializationWithData:[json dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeJSON] delegate:self];
 }

referance:

  1. https://github.com/RestKit/RestKit/wiki/Tutorial-%3A-Introduction-to-RestKit
  2. https://github.com/RestKit/RestKit/wiki/Posting-NSDictionary-as-JSON

Thanks Nikhil

Upvotes: 6

Related Questions