使用UIWebview使用javascript调用swift函数 [英] Call swift function with javascript using UIWebview

查看:129
本文介绍了使用UIWebview使用javascript调用swift函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果有人问过我,我很抱歉,但我无法找到任何答案或解决方案。我期待从UIWebView调用JavaScript函数并在swift中监听它。我找到的任何例子都使用WKWebView。必须有一种简单的方法来收听如下的JavaScript函数:

I apologize if this has been asked but I was unable to find any answer or solution. I am looking to call a JavaScript function from a "UIWebView" and listen for it in swift. Any example I have found uses "WKWebView". There has to be an easy way to listen to a JavaScript function like the below:

// HTML / JS
<div id ="myDiv" onclick="listenInSwift()">myItem</div>

这是否可以通过UIWebView实现?谢谢大家!

Is this possible with a UIWebView? Thanks all!

推荐答案

实施 listenInSwift 这样:

function listenInSwift() {
    window.location = 'yoururlscheme://somehost?greeting=hello'
} 

然后在 UIWebViewDelegate 类:

func webView(_ webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType navigationType: UIWebViewNavigationType) -> Bool {
    if request.URL.scheme == 'yoururlscheme' {
        print('Hello JavaScript...')
    }
}

不要忘记在Xcode中注册您的URL Scheme(在本例中为'yoururlscheme')。

Don't forget to register your URL Scheme (in this case 'yoururlscheme') in Xcode.

要在Web视图中加载本地文件,请尝试以下操作:

To load a local file in the web view, try this:

let baseURL = NSURL.fileURLWithPath(NSBundle.mainBundle().bundlePath);
let relativePath = "www/\(file)"
let fileURL = NSURL(string: relativePath, relativeToURL: baseURL);
let URLRequest = NSURLRequest(URL: fileURL!);
webView.loadRequest(URLRequest)

这篇关于使用UIWebview使用javascript调用swift函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆