Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone SDK: control websites in UIWebView programmatically

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

like image 279
dan Avatar asked Nov 06 '22 17:11

dan


1 Answers

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
like image 66
Frank Krueger Avatar answered Nov 12 '22 15:11

Frank Krueger