繁体   English   中英

使用UIWebView从HTML代码调用目标c代码中的方法

[英]Invoke method in objective c code from HTML code using UIWebView

我的iOS应用程序中有.html文件。 HTML文件使用onClick方法有几个div块。 当我点击这些块时,我在Web视图中调用了一些javascript代码,但我还需要在源代码中了解这些事件。

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

我可以做这个吗 谢谢。

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

以下网址有助于实现这一目标

如何从Javascript调用Objective C方法并将数据发送回iOS中的Javascript?

没有办法执行,我们通过导航到其他页面来解决方法,并且在导航期间,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>

Objective-C代码

当您单击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 ];
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM