我的 View Controller 中嵌入了一个 UIWebView,如下所示:
我的 WebView ( _graphTotal
) 有一个导出,我可以成功加载 test.html
的内容在其中使用:
[_graphTotal loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"test" ofType:@"html"]isDirectory:NO]]];
我现在正尝试将数据传递到 WebView ,但没有成功。我添加了 <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 中看到“Testing...”,但我没有看到警报,也没有看到返回的“hi!”字符串。
知道我做错了什么吗?
最佳答案
好吧,问题是您试图在 webview 有机会加载页面之前评估您的 javascript。先采纳<UIWebViewDelegate>
协议(protocol)进入你的 View Controller :
@interface ViewController : UIViewController <UIWebViewDelegate>
然后将您的 webview 的委托(delegate)连接到您的 View Controller ,发出请求并最终实现 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 .
关于ios - 将数据传入和传出嵌入式 UIWebView,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17117713/