如何将数据从swift发送到javascript,并将其显示在我的网络视图中? [英] How can I send data from swift to javascript and display them in my web view?

查看:94
本文介绍了如何将数据从swift发送到javascript,并将其显示在我的网络视图中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我找到了一些示例,该示例显示了如何在本机代码和JS之间进行通信,但没有关于如何传输本机"数据并将其显示在Web视图中的任何示例. 谢谢.

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.

推荐答案

您应该要求位置管理器为您更新位置,而不是设置1秒的NSTimer自行完成.并将数据传递给Javascript,可以使用WKWebViewevaluateJavaScript方法:

You should ask the Location Manager to update the location for you instead of setting up a 1-second NSTimer to do it yourself. And to pass data to Javascript, you can use evaluateJavaScript method of 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
            }
        }
    }
}

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).

这篇关于如何将数据从swift发送到javascript,并将其显示在我的网络视图中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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