Thursday, 8 August 2013

iOS App needs to POST to PHP script and then parse returned XML

iOS App needs to POST to PHP script and then parse returned XML

I have a database of images stored in a table with columns such as
"ImageName", "ImageCaption", and "EventName".
I wanna do a query and grab all images with a specific "EventName" - as
selected by the user - like so:
$EventName = $_POST['EventName'];
$query = "SELECT * from ImageGalleryTable WHERE EventName = '". $EventName
. "'";
The tricky part is that this user-selection is not coming from an HTML
form, its coming from within an iPhone App. Here's my Objective-C code for
that:
NSString *myRequestString = [NSString stringWithFormat:@"EventName=%@",
eventUserChose];
NSData *myRequestData = [NSData dataWithBytes:[myRequestString UTF8String]
length:[myRequestString length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
initWithURL:[NSURL URLWithString:
@"http://mydomain.com/GetGalleryImages.php"]];
[request setHTTPMethod: @"POST"];
[request setValue:@"application/x-www-form-urlencoded"
forHTTPHeaderField:@"content-type"];
[request setHTTPBody: myRequestData];
NSURLResponse *response;
NSError *err;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request
returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[returnData bytes]];
NSLog(@"responseData: %@", content);
All this works: the data I get back via responseData is good - its the XML
generated by the PHP script I'm calling up top and everything is clean
there. The POSTing from the App also works - so its all good.
So my question is this: how do I parse this sucker?
I've done tons of parsing using NSXMLParser (and yes, I know its not the
best parser out there - lets please not get into that discussion here :-))
- but all the XML I parse usually comes ready from the server - its not
dependent on any POSTed values, if you get my meaning. Usually I do the
parsing like this:
NSURL *url = [NSURL URLWithString:@"http://mydomain.com/makeMyXML.php"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser parse];
And then I'm off and running. But here I gotta both POST something - which
I think I can only do with the NSURLConnection code I included up top -
and then I also have to parse it - which I usually do with the NSXMLParser
code I included -- but they seem to conflict. I mean they both initiate a
request process, don't they?
So how exactly should I be going about doing this? What's the correct way?

No comments:

Post a Comment