我找到了一些示例,说明如何在本机代码和Js之间进行通信,但没有关于如何传输我的“本机”数据并在Web视图中显示它们.
谢谢.
import UIKitimport WebKitimport CoreLocationclass 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可以看到它不断更新(就像你在公园里跑步一样).
总结以上是内存溢出为你收集整理的如何将数据从swift发送到javascript并在我的Web视图中显示?全部内容,希望文章能够帮你解决如何将数据从swift发送到javascript并在我的Web视图中显示?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)