views:

992

answers:

1

I need to control a website that is loaded into a UIWebView like sending post data and using get requests. After each request the response should be loaded as a string into a variable.

The reason for this is that I'm trying to fetch data from a website that has no public web api and using cookie based user authentication. So I want to login the user, fetch some data from that site and present the results.

Is something like this posible?

EDIT: I just came across the method stringByEvaluatingJavaScriptFromString. Would it be posible to use this method to control the content within the UIWebView with JS? Like submitting a web form and wait for the page to finish loading and getting the response data?

EDIT 2: Just found a framework that might be helpful ASIHTTPRequest

+2  A: 

Sure it's possible. Just do the networking code yourself and then dump the resulting HTML int othe UIWebView.

// Do your POST
NSURL *url = [NSURL URLWithString:"http://stackoverflow.com"];
NSString *body = @"laadeedaa";

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding:NSUTF8StringEncoding]];

// Dump the response to the UIWebView
[webView loadRequest:request];

If you want to process the response before displaying it, then you will want to do something along the lines of:

NSURLResponse *response = nil;
NSError *error = nil;
NSData *respData = [NSURLConnection sendSynchronousRequest:request 
                                         returningResponse:&response 
                                                     error:&error];
NSString *respString = [[[NSString alloc] initWithData:respData 
                                              encoding:NSUTF8StringEncoding] autorelease];

NSString *htmlString = [self doSomethingWith:respString];

[webView loadHTMLString:htmlString baseURL:@"http://stackoverflow.com"];

Also keep in mind that you can use JavaScript to control the browser:

- (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script
Frank Krueger
Thanks for your fast reply.Will the NSMutableURLRequest take care of the auth web cookies? Or will it just send the request - like fire and forget?
dan
I don't know to be honest. I've been using MonoTouch for last 6 months. Apple has good docs; otherwise, open a new SO question.
Frank Krueger