xcode 如何将数据从 swift 发送到 javascript 并在我的 Web 视图中显示它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37820666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 08:53:49  来源:igfitidea点击:

How can I send data from swift to javascript and display them in my web view?

javascripthtmlxcodeswifthybrid-mobile-app

提问by Lola

I am doing an iOS hybrid app using swift 2 and HTML/Javascript. I have a native shell which get some information from the calendar and the GPS. I would like to display those information in my WKWebView and update them every seconds. I am working with local HTML.

我正在使用 swift 2 和 HTML/Javascript 做一个 iOS 混合应用程序。我有一个本机外壳,它从日历和 GPS 中获取一些信息。我想在我的 WKWebView 中显示这些信息并每秒钟更新一次。我正在使用本地 HTML。

I have found some example showing how to communicate between the native code and the JS but nothing on how to transfer my "native" datas and display them in the web view. Thanks.

我找到了一些示例,展示了如何在本机代码和 JS 之间进行通信,但没有关于如何传输我的“本机”数据并将它们显示在 Web 视图中。谢谢。

回答by Code Different

You should ask the Location Manager to update the location for you instead of setting up a 1-second NSTimerto do it yourself. And to pass data to Javascript, you can use evaluateJavaScriptmethod of WKWebView:

您应该要求位置管理器为您更新位置,而不是NSTimer自己设置 1 秒钟。并将数据传递给 Javascript,您可以使用以下evaluateJavaScript方法WKWebView

import UIKit
import WebKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
    weak var webView: WKWebView!
    let locationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        createWebView()
        locationManager.delegate = self
        locationManager.startUpdatingLocation()
        locationManager.requestWhenInUseAuthorization()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func createWebView() {
        let url = NSBundle.mainBundle().URLForResource("my_page", withExtension: "html")!

        let webView = WKWebView()
        webView.loadFileURL(url, allowingReadAccessToURL: url)
        webView.translatesAutoresizingMaskIntoConstraints = false

        self.view.addSubview(webView)

        // Auto Layout
        let views = ["webView": webView]
        let c1 = NSLayoutConstraint.constraintsWithVisualFormat("H:|[webView]|", options: [], metrics: nil, views: views)
        let c2 = NSLayoutConstraint.constraintsWithVisualFormat("V:[webView]|", options: [], metrics: nil, views: views)
        let c3 = NSLayoutConstraint(item: webView, attribute: .Top, relatedBy: .Equal, toItem: self.topLayoutGuide , attribute: .Bottom, multiplier: 1, constant: 0)
        NSLayoutConstraint.activateConstraints(c1 + c2 + [c3])

        // Pass the reference to the View's Controller
        self.webView = webView
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let lastLocation = locations.last!

        let dict = [
            "lat": lastLocation.coordinate.latitude,
            "long": lastLocation.coordinate.longitude
        ]
        let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: [])
        let jsonString = String(data: jsonData, encoding: NSUTF8StringEncoding)!

        // Send the location update to the page
        self.webView.evaluateJavaScript("updateLocation(\(jsonString))") { result, error in
            guard error == nil else {
                print(error)
                return
            }
        }
    }
}

And my_page.html:

并且my_page.html

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width; initial-scale=1.0">
    <title>This is a test page</title>
    <script type="text/javascript">
    function updateLocation(data)
    {
        var ele = document.getElementById('location');
        ele.innerHTML = 'Last location: lat = ' + data['lat'] + ', long = ' + data['long'];
    }
    </script>
</head>
<body>
    <p id="location">Last location:</p>
</body>
</html>

If you are testing this in the Simulator, choose Debug > Location > City Run to see it update continuously (as if you are running through a park).

如果您在模拟器中对此进行测试,请选择“调试”>“位置”>“城市跑步”以查看它持续更新(就像您在公园中奔跑一样)。