GET forms are the easiest to do. You just tack on your variables to the end of the URL, like this:
Then you could use your standard NSURLDownload to fetch the file.
A POST form is pretty much the same thing, except you need to specify that you are sending a POST, and you need to stick your variables into the http body instead of tacking them onto the end of the URL.
Here's how to setup the URL request for a POST:
NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
And you can use this to setup your NSURLDownload. Pretty simple huh?
There is one last thing we need to tackle before you can start using this in your finished product. You need to make sure that the strings you use are properly encoded to go into your string. For example, imagine that one of your keys is called "name" and it's value is "Bob & Cindy". You can't have spaces like that in your URL (or inside the post string), so you'd have to escape the spaces like this "Bob%20&%20Cindy". But that's not all...
You would also need to encode the '&' symbol, because it has special meaning. (To seperate one key,value pair from another). And you'd also need to encode any '?' symbols, and any '=' symbols, and so on. But we don't want to have to write a custom method to do all this. Not when apple has already provided such a huge API for use to use. So what can we use to do this for use in 1 or 2 lines of code?
At first glance it looks like NSString's stringByAddingPercentEscapesUsingEncoding: method might work. But if you try it with the "Bob & Cindy" string above you'll find that it only encodes the spaces, and leaves the '&' symbol. But we see from the method's documentation that it uses Core Foundations CFURLCreateStringByAddingPercentEscapes method to do it's dirty work. And we can use this to do ours as well. Here is a method to do what we want:
- (NSString *)urlEncodeValue:(NSString *)str
NSString *result = (NSString *) CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)str, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8);
return [result autorelease];
So to use the method you would write something like this:
NSString *post = [NSString stringWithFormat:@"key1=%@&key2=%@",