向嵌入式 UIWebView 传递数据和从嵌入式 UIWebView 传递数据 [英] Passing Data To and From an Embedded UIWebView

查看:16
本文介绍了向嵌入式 UIWebView 传递数据和从嵌入式 UIWebView 传递数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的视图控制器中嵌入了一个 UIWebView,如下所示:

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

我的 Web 视图 (_graphTotal) 有一个出口,我可以使用以下方法成功加载 test.html 的内容:

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]]];

我现在正在尝试将数据传递到 Web 视图,但没有任何运气.我已经添加了 <UIWebViewDelegate> 这就是我正在尝试的:

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);

这是我项目中test.html的内容:

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

我可以在我的 webView 中看到正在测试...",但我没有看到警报,也没有看到返回的嗨!"字符串.

I can see "Testing..." in my webView, but I'm not seeing the alert nor the returned "hi!" string.

知道我做错了什么吗?

推荐答案

问题是你试图在 webview 有机会加载页面之前评估你的 javascript.首先将 <UIWebViewDelegate> 协议引入您的视图控制器:

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>

然后将 webview 的代理连接到视图控制器,发出请求并最终实现 委托方法.这是在 webview 完成加载时通知您的通知:

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:当您以这种方式评估 javascript 时必须注意的限制之一是您的脚本必须在 10 秒内执行.因此,例如,如果您等待超过 10 秒以解除警报,您将收到错误消息(等待 10 秒后返回失败).在文档.

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.

这篇关于向嵌入式 UIWebView 传递数据和从嵌入式 UIWebView 传递数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆