Javascript从UIWebView调用Swift

Javascript从UIWebView调用Swift

本文介绍了Javascript从UIWebView调用Swift的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从UIWebView中的javascript函数调用到iOS 10中的Swift。我已经设置了一个非常基本的项目,试图让它工作,代码如下。

I am trying to make a call from a javascript function in a UIWebView to Swift in iOS 10. I have setup a very basic project just to try and get this working, the code is below.

import UIKit

class ViewController: UIViewController, UIWebViewDelegate  {
  @IBOutlet var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = Bundle.main.url(forResource: "products", withExtension: "html")
        let request = NSURLRequest(url: url! as URL)
        webView.loadRequest(request as URLRequest)
    }

    @IBAction func closeDocumentViewer() {
        displayView.isHidden = true;
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

如果我只是一个从javascript函数接收字符串,我还需要添加到上面的内容?

If I just one to receive a string from a javascript function what would I have to add to the above?

推荐答案

您必须自定义 URL Scheme ,例如 myawesomeapp 并使用以下方法拦截对它的请求:

You must a custom URL Scheme such as myawesomeapp and intercept requests to it using:

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool

使用触发对本机代码的调用window.location = myawesomeapp:/ / hello = world ,并获取您从本机代码中的 request.URL.query 传递的查询参数。

Fire a call to native code using window.location=myawesomeapp://hello=world, and get the query params you pass from request.URL.query in the native code.

有关详细信息,请在此处查看有关 UIWebView 的问题:

For more information, see my question about UIWebViews here: JavaScript synchronous native communication to WKWebView

这篇关于Javascript从UIWebView调用Swift的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 07:59