开发者

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 res开发者_开发知识库ponse 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


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜