将数据传入和传出embedded式UIWebView
我的视图控制器中embedded了一个UIWebView,如下所示:
我有我的networking视图( _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);
这里是我的项目中的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>
协议:
@interface ViewController : UIViewController <UIWebViewDelegate>
然后将你的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); }
PS:当你以这种方式评估JavaScript时必须注意的一个限制是脚本必须在10秒内执行。 因此,例如,如果您等待了超过10秒的时间来解除警报,则会发生错误( 等待10秒后未能返回 )。 详细了解文档中的限制。