【问题标题】:Invoke method in objective c code from HTML code using UIWebView使用 UIWebView 从 HTML 代码调用目标 c 代码中的方法
【发布时间】:2013-03-10 08:39:00
【问题描述】:

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

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

我可以做这些事情吗?谢谢。

【问题讨论】:

    标签: javascript ios uiwebview


    【解决方案1】:

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

    下面的网址有助于做到这一点

    How to invoke Objective C method from Javascript and send back data to Javascript in 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>
    

    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 ];
    }
    

    【讨论】:

    • 小心安全隐患!
    • 你能说得更详细些吗?
    • 假设你的类中有一个名为 getSecretToken 的方法。然后你可以从 Javascript 调用它
    • 谢谢兄弟...这真的是一个很棒的答案。我从过去 2 天开始就卡住了。我已经发布了我的 q 但没有得到任何有价值的解决方案。终于你的回答解决了我的问题...非常感谢
    • 如何使用它从服务器获取值到本地方法调用?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-11-03
    • 1970-01-01
    相关资源
    最近更新 更多