It has been two weeks with a lot of work and a seriously lack of time to update the blog, but we are back again.
This week code snippet is about sending data to web services, XML and JSON are most used technologies used today but maybe some of your has to send data to an older php web page that receives data from a form by GET, POST or both of them. How could we accomplish that?
Let's see a code snippet to do it synchronously, later we'll publish a new entry with the asynchronous method.
First thig to do is to create the NSURL object which we are going to make the request to. If it has any GET parameters we should put them in the URL String.
NSURL *url = [NSURL urlWithString:@"http://www.fiveflamesmobile.com/login.php?from=mobile"];
After that we have to create a NSMutableURLRequest in order to put the post parameter.
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHttpMethod:@"POST"];
And now we only have to put in the HTTPBody the form variables as URL encoding like "key1=value1&key2=value2..." as a NSData object.
NSString *formValues = [NSString stringWithFormat:@"name=%@&device=%@", @"FiveFlames", @"iPhone"];
NSData *formData = [formValues dataUsingEncoding:NSUTF8StringEncoding];
[urlRequest setHttpBody:formData];
And now, we only just to make the request and save the response.
NSURLResponse *response;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:urlRequest response:&response error:&error];
NSLog (@"Response: %@", responseData);
That's all, with this code snippet you could keep your older php or asp pages and reuse it to develop a server-client iOS app.
Enjoy it!
No comments:
Post a Comment