javascript - 如何将数据从 swift 发送到 javascript 并在我的 WebView 中显示它们?

标签 javascript html xcode swift hybrid-mobile-app

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

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

最佳答案

您应该要求位置管理器为您更新位置,而不是设置一个 1 秒的 NSTimer 来自己做。并且要将数据传递给 Javascript,您可以使用 WKWebViewevaluateJavaScript 方法:

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>

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

关于javascript - 如何将数据从 swift 发送到 javascript 并在我的 WebView 中显示它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37820666/

相关文章:

javascript - 使用 jquery 将外部 css 样式表应用于动态添加的 html 内容

javascript - 无法调用休息电话

Android WebView 字体最初未呈现

javascript - 使用 PHP 验证 HTML 错误

iphone - 在已发布的 iPhone 应用程序中构建优化级别设置

ios - XCode:如何找到所有然后删除所有禁用约束

ios - 解析 Facebook 用户登录,执行 segue

javascript - 停止在jsp中将 "<"转换为 "&lt;"

javascript - 搜索最长前缀

javascript - 使用 jQuery 隐藏/显示功能时,表单提交按钮不起作用