Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
212 views
in Technique[技术] by (71.8m points)

ios - Passing Data To and From an Embedded UIWebView

I have a UIWebView embedded in my view controller like this:

enter image description here

I have an outlet to my web view (_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]]];

I'm now trying to pass data to the web view and haven't had any luck. I have added the <UIWebViewDelegate> and here's what I'm trying:

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

And here are the contents 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 can see "Testing..." in my webView, but I'm not seeing the alert nor the returned "hi!" string.

Any idea what I'm doing wrong?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Well the problem is that you tried to evaluate your javascript before the webview had the chance to load the page. First adopt the <UIWebViewDelegate> protocol into your view controller:

@interface ViewController : UIViewController <UIWebViewDelegate>

Then connect the delegate of your webview to your view controller, make the request and finally implement the delegate methods. Here is the one that notifies you when the webview has finished loading:

- (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 limits you must be aware of when you're evaluating javascript this way is that your script must be executed within 10 seconds. So if for example you've waited more than 10 secs to dismiss the alert you would get an error (failed to return after waiting 10 seconds). Find more about the limitations in the docs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...