将数据传入和传出嵌入式UIWebView

Cli*_*rum 8 uiwebview ios

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

在此输入图像描述

我有一个网络视图(_graphTotal)的插座,我可以test.html使用这个成功加载其中的内容:

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

我现在正试图将数据传递到Web视图并且没有运气.我已经添加了<UIWebViewDelegate>以及我正在尝试的内容:

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

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

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

我可以在我的webView中看到"Testing ...",但我没有看到警报,也没有看到"hi!" 串.

知道我做错了什么吗?

All*_*ian 16

那么问题是你在webview有机会加载页面之前试图评估你的javascript.首先在<UIWebViewDelegate>您的视图控制器中采用该协议:

@interface ViewController : UIViewController <UIWebViewDelegate>
Run Code Online (Sandbox Code Playgroud)

然后将webview的委托连接到视图控制器,发出请求并最终实现委托方法.这是在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);
}
Run Code Online (Sandbox Code Playgroud)

PS:当您以这种方式评估javascript时必须注意的一个限制是您的脚本必须在10秒内执行.因此,例如,如果您等待超过10秒以消除警报,则会出现错误(等待10秒后无法返回).详细了解文档中的限制.