Passing Data To and From an Embedded UIWebView

前端 未结 1 1000
感情败类
感情败类 2020-12-09 00:17

I have a UIWebView embedded in my view controller like this:

\"enter

I have an

相关标签:
1条回答
  • 2020-12-09 00:28

    Well the problem is that you tried to evaluate your javascript before the webview had the chance to load the page. First adopt the <UIWebViewDelegate> protocol into your view controller:

    @interface ViewController : UIViewController <UIWebViewDelegate>
    

    Then connect the delegate of your webview to your view controller, make the request and finally implement the delegate methods. Here is the one that notifies you when the webview has finished loading:

    - (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: One of the limits you must be aware of when you're evaluating javascript this way is that your script must be executed within 10 seconds. So if for example you've waited more than 10 secs to dismiss the alert you would get an error (failed to return after waiting 10 seconds). Find more about the limitations in the docs.

    0 讨论(0)
提交回复
热议问题