我的视图控制器中嵌入了一个UIWebView,如下所示:
我的网络视图(_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中看到“测试...”,但我没有看到警报,也没有看到“hi!”字符串。
知道我做错了吗?
答案 0 :(得分:16)
问题是你在webview有机会加载页面之前试图评估你的javascript。首先在视图控制器中采用<UIWebViewDelegate>
协议:
@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。