I've been trying to figure this out for weeks and i still get nothing. I am using the ASIHTTPRequest and ive successfully sent the data to a server and now I need to get the response XML,parse it and save the elements to each labeled NSString so I can post it to the server. Does anyone have an idea on how to do this?
From looking at the How to Use page, I think what you want to do is implement methods that can be called when the request is complete. For example, say you have a method done:
that you want to be called when your request completes. You can set that method as your "finished" selector on the request:
NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
ASIHTTPRequest *request = [[[ASIHTTPRequest alloc] initWithURL:url] autorelease];
[request setDelegate:self];
[request setDidFinishSelector:@selector(done:)];
Then later, you implement the done:
method:
- (void)done:(ASIHTTPRequest *)request
{
NSString *response = [request responseString];
}
This is all assuming you're sending the requests asynchronously; if you're using synchronous calls, you can just use the responseString
property on the request.
Get a copy of an XML library for the iPhone if you have other than trivial XML parsing needs.
I've used Google's GDataXMLNode for this before, but I would probably use KissXML for future work, because it's nearer NSXML (the Apple library which doesn't ship for the iphone unfortunately).
Here's a way to parse out the response, here I'm looking for errors you might typically see from a Rails server, along the lines of:
<errors><error>Description of what went wrong</error></errors>
You can see that I get the 'request' object back from the library, and I feed the response string into a GDataXMLDocument.
GDataXMLDocument* root = [[GDataXMLDocument alloc] initWithXMLString:[request responseString] options:0 error:nil];
// Parse the error strings
NSArray* errors = [root nodesForXPath:@"//errors/error" error:nil];
// What is the first error string.... etc......
NSString* firstError = [[errors objectAtIndex:0] stringValue];
The returned array here contains a list of nodes that match that path in the XML. If you're not familiar with XPath, it's not hard to learn, and useful for pulling data out of an XML response. Calling stringValue against the element returned in the array will return the text between the elements in the example above.
You can of course populate a dictionary, etc. with the returned XML data. Make sense?