HTTP POST from iOS

This post shares the code to do a simple HTTP POST from iOS.

NSString *post = [NSString stringWithFormat:@"key1=%@&key2=%@",value1,value2];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *urlString = @"http://someurl";
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

REST API – Testing

So, you’ve written a REST API that handles the following request methods:
GET
POST
DELETE
PUT

Now, you want to test them. I’ve found two great clients in order to test your REST APIs.

POSTER (for users of firefox)  AND Simple REST Client

Happy RESTing !

Mad World by Gary Jules – in my voice and on my guitar!

A bright Saturday afternoon and I can’t stop humming this song. Time to record !

Here is the Music Player. You need to installl flash player to show this cool thing!

“Expected Expression” when declaring and initializing NSInteger in a switch statement

I ran across a strange problem today. Tried something like this:

switch(controlVariable) {

case 0:

NSInteger x = kSomeConstant;

// some other code…

break;

case 1:

// …

default:

// …

}

And to my surprise, XCode complained saying that “Parse error: Expected Expression”. Upon googling, this is what I found.

So, the solution is to put some statement before you initialize NSInteger. If there is no statement that logically fit, you can simply insert a semi-colon “;” before declaring and initializing the integer.

switch(controlVariable) {

case 0:

;

NSInteger x = kSomeConstant;

// some other code…

break;

case 1:

// …

default:

// …

}

A Tip on programming Table Views

I found a great post on organizing your code while writing code around Table View/Table View Delegate. It details how one can organize sections and rows by making them enums instead of using numbers all over the delegate methods. See for yourself:

Click the post here.