如何将数据从swift发送到javascript并在我的Web视图中显示?
发布时间:2020-12-14 05:39:57 所属栏目:百科 来源:网络整理
导读:我正在使用 swift 2和 HTML / Javascript进行iOS混合应用程序.我有一个本机shell,从日历和GPS获取一些信息.我想在我的WKWebView中显示这些信息,并每隔一秒更新一次.我正在使用本地HTML. 我找到了一些示例,说明如何在本机代码和JS之间进行通信,但没有关于如何
我正在使用
swift 2和
HTML /
Javascript进行iOS混合应用程序.我有一个本机shell,从日历和GPS获取一些信息.我想在我的WKWebView中显示这些信息,并每隔一秒更新一次.我正在使用本地HTML.
我找到了一些示例,说明如何在本机代码和JS之间进行通信,但没有关于如何传输我的“本机”数据并在Web视图中显示它们.
您应该要求位置管理员为您更新位置,而不是设置1秒钟的NSTimer来自行完成.要将数据传递给Javascript,您可以使用WKWebView的evaluate
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]|",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> 如果您在模拟器中测试它,请选择Debug>位置> City Run可以看到它不断更新(就像你在公园里跑步一样). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |