【问题标题】:Passing Data To and From an Embedded UIWebView向嵌入式 UIWebView 传递数据和从嵌入式 UIWebView 传递数据
【发布时间】:2013-06-14 21:44:24
【问题描述】:

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

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

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

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

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 中看到“正在测试...”,但我没有看到警报,也没有看到返回的“嗨!”字符串。

知道我做错了什么吗?

【问题讨论】:

    标签: ios uiwebview


    【解决方案1】:

    问题是您试图在 webview 有机会加载页面之前评估您的 javascript。首先在您的视图控制器中采用&lt;UIWebViewDelegate&gt; 协议:

    @interface ViewController : UIViewController <UIWebViewDelegate>
    

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

    - (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 秒后返回失败)。了解有关限制的更多信息in the docs

    【讨论】:

    • 太棒了,效果很好。我已经添加了委托,但没有在 Interface Builder 中连接它。我还需要webViewDidFinishLoad 方法。谢谢!
    猜你喜欢
    • 2015-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2012-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多