0

I'm trying to post to a rails backend from Objective-C and JSONKit and am having difficulty getting my results published. I keep getting back a null recordset from my server.

[dictionary setValue:(@"bar")  forKey:@"foo"];

NSString *JSON = [dictionary JSONString];
NSData *theData = [JSON dataUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString: myUrl];

NSString *postLength = [NSString stringWithFormat:@"%d", [theData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSError *error = NULL;
NSURLResponse *response = nil;

[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:theData];
NSData *result = [NSURLConnection sendSynchronousRequest:request
                                       returningResponse:&response error:&error];

NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
NSLog(resultString);

Is there something I'm missing? the JSON seems to be serializing correctly

{"foo":"bar"}

Any help would be greatly appreciated.
Thanks!

mat
  • 11
  • 1
  • Apart from the parentheses in setValue:(@"bar"), which should not be the problem, I do not see anything strange here. Try to change the cachePolicy of the request to NSURLRequestReloadIgnoringCacheData, it might help. – Davyd Geyl Sep 26 '11 at 04:57
  • Thanks, Davyd.i tried adding [request setCachePolicy:NSURLRequestReloadIgnoringCacheData]; to the above and I'm still having the issue. – mat Sep 26 '11 at 11:47
  • Does the server get the data you send? – Davyd Geyl Sep 26 '11 at 11:57
  • i ended up changing just this line setValue:@"application/json-rpc" forHTTPHeaderField:@"Content-Type"]; to [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; and it worked. Thanks buddy! – mat Sep 26 '11 at 23:30

1 Answers1

1

Just changed the setValue from json-rpc to json and it worked like a champ.

[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
**[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];**
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setHTTPBody:theData];
mat
  • 11
  • 1
  • Good catch. I was not sure about content type, I thought you put those one for a reason. It is good you've found it. – Davyd Geyl Sep 27 '11 at 00:45