2012-01-16 33 views
36

我试图使用该函数来调用一个HTML页面的JavaScript调用的Javascript -使用UIWebView的

View did load function 
{ 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *writablePath = [documentsDirectory stringByAppendingPathComponent:@"BasicGraph.html"]; 
    NSURL *urlStr = [NSURL fileURLWithPath:writablePath]; 

    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    NSString *myPathInfo = [[NSBundle mainBundle] pathForResource:@"BasicGraph" ofType:@"html"]; 
    [fileManager copyItemAtPath:myPathInfo toPath:writablePath error:NULL]; 

    [graphView loadRequest:[NSURLRequest requestWithURL:urlStr]]; 
} 

- (void) webViewDidFinishLoad:(UIWebView *)webView 
{ 
    [graphView stringByEvaluatingJavaScriptFromString:@"methodName()"]; 
} 

下面是HTML页面的JavaScript -

<script> 
    function methodName() 
     { 
     // code to draw graph 
     } 

然而,函数methodName()没有被调用,但在window.onload = function()之后,一切正常。

我正在尝试将RGraphs整合到我的应用程序中,并且Basic.html是写入javascript的html页面。

这将是巨大的,如果有人可以帮助我了这一点。

+0

嘿,如果你不介意,你可以请你分享你的示例代码,我可以从本地iOS代码调用rgrpahs吗?这将是非常有益的。从上一个星期我努力使它工作。 – iamMobile 2012-07-27 11:12:07

+1

我刚刚在UIWebview的Javascript运行主题上创建了一个优雅的演示,请参考:http://creiapp.blogspot.hk/2013/04/uiwebview-javascript.html – 2013-04-18 05:43:49

回答

66

简单:在加载页面之前,您尝试从Objective-C执行JS函数。

落实UIWebView's delegate methodwebViewDidFinishLoad:在UIViewController,并在那里你打电话[graphView stringByEvaluatingJavaScriptFromString:@"methodName()"];,以确保函数被调用后,页面已经被加载。

+0

我试图做到这一点,但它仍然不是工作..我已经改变了问题的代码,但似乎没有工作.. – learner2010 2012-01-16 22:02:27

+7

这是一个非常有效的问题,并没有一个愚蠢的一个..谢谢。我忘了设置委托..现在代码工作... – learner2010 2012-01-16 22:06:29

9

澄清一点点。

.H - 落实UIWebViewDelegate

@interface YourViewController : UIViewController <UIWebViewDelegate> 
@property (weak, nonatomic) IBOutlet UIWebView *webView; 
@end 

.M

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    NSString *path = @"http://www.google.com"; 
    [_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:path]]]; 
    _webView.delegate = self; //Set the webviews delegate to this 
} 

- (void) webViewDidFinishLoad:(UIWebView *)webView 
{ 
    //Execute javascript method or pure javascript if needed 
    [_webView stringByEvaluatingJavaScriptFromString:@"methodName();"]; 
} 

你也可以从情节串连图板指定代表,而不是在代码中做这件事的。