Transferring data to and from the built-in UIWebView

I have a UIWebView built into my view controller as follows:

enter image description here

I have access to my _graphTotal ( _graphTotal ) and I can successfully load the contents of test.html in it using this:

[_graphTotal loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];

Now I am trying to pass data to a web view and no luck. I added <UIWebViewDelegate> and here is what I am trying:

 NSString *userName = [_graphTotal stringByEvaluatingJavaScriptFromString:@"testFunction()"]; NSLog(@"Web response: %@",userName); 

And here is the content of test.html in my project:

 <html> <head></head> <body> Testing... <script type="text/javascript"> function testFunction() { alert("made it!"); return "hi!"; } </script> </body> </html> 

I see "Testing ..." in my web browser, but I do not see a warning and do not return "hello!". line.

Any idea what I'm doing wrong?

+7
source share
1 answer

Well, the problem is that you tried to evaluate your javascript before the webview was able to load the page. First, transfer the <UIWebViewDelegate> protocol to your view controller:

 @interface ViewController : UIViewController <UIWebViewDelegate> 

Then connect the delegate of your web view to the view controller, execute the request and finally execute the delegation methods . Here is the one that notifies you of the completion of loading the web page:

 - (void)viewDidLoad { [super viewDidLoad]; [self.graphTotal loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { NSString *userName = [self.graphTotal stringByEvaluatingJavaScriptFromString:@"testFunction()"]; NSLog(@"Web response: %@",userName); } 

PS: One of the limitations that you should know when you evaluate javascript in this way is that your script must be executed within 10 seconds. So if, for example, you waited more than 10 seconds to cancel the warning, you will receive an error message (failed to return after waiting 10 seconds). Learn more about document restrictions.

+14
source

All Articles