首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将数据从swift发送到javascript并在我的web视图中显示?

如何将数据从swift发送到javascript并在我的web视图中显示?
EN

Stack Overflow用户
提问于 2016-06-15 03:36:03
回答 1查看 10.2K关注 0票数 8

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-06-15 10:54:47

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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
<!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>

如果您正在模拟器中对其进行测试,请选择Debug > Location > City Run以查看其持续更新(就像您在公园中跑步一样)。

票数 18
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37820666

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档