使用UIWebView从HTML代码中调用objective - c代码中的方法

Invoke method in objective c code from HTML code using UIWebView

本文关键字:代码 方法 objective 调用 HTML UIWebView 使用      更新时间:2023-09-26

我有。HTML文件在我的iOS应用程序。HTML文件有几个div块与onClick方法。当我点击这些块,我调用一些javascript代码在web视图,但我也需要知道这些事件在我的源代码。

例如,当我点击web元素和onClick被调用时,我需要在代码中调用一些方法,例如- (void)didTouchedWebElementWithId

我能做这个吗?谢谢。

在JS中调用Objective-C的方法:

下面的url有助于做到这一点

如何调用Objective C方法从Javascript和发送数据回Javascript在iOS?

没有办法执行,我们通过导航到其他页面来解决这个问题,在导航期间,webview委托将监视导航的前缀并执行我们指定的方法。

sample . html

<html>
    <head>
        <script type='text/javascript'>
            function getText()
            {
                return document.getElementById('txtinput').value;
            }
            function locationChange()
            {
                window.location = 'ios:webToNativeCall';
            }
        </script>
    </head>
    <body style='overflow-x:hidden;overflow-y:hidden;'>
        <h2 style = "font-size:16px;" align='center'>Hi Welcome to Webpage</h2>
        <br/>
        <p align='center' style = "font-size:12px;">Please Click the button after entering the text</p>
        <br/>
        <center>
            <input type='text' style='width:90px;height:30px;' id='txtinput'/>
        </center>
        <br/>
        <center>
            <input type='button' style='width:90px;height:30px;' onclick='locationChange()' value='click me'>
        </center>
    </body>
</html>
<<p> objective - c代码/strong>

当你点击html页面中的按钮时,下面的委托将被触发,导航将被取消,因为我们返回NO并且各自的方法被调用

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    if ([[[request URL] absoluteString] hasPrefix:@"ios:"]) {
        // Call the given selector
        [self performSelector:@selector(webToNativeCall)];        
        // Cancel the location change
        return NO;
    }
    return YES;
}
- (void)webToNativeCall
{
    NSString *returnvalue =  [self.webviewForHtml stringByEvaluatingJavaScriptFromString:@"getText()"];
    self.valueFromBrowser.text = [NSString stringWithFormat:@"From browser : %@", returnvalue ];
}