2016-06-14 31 views
6

我正在做一個使用swift 2和HTML/Javascript的iOS混合應用程序。我有一個本地shell從日曆和GPS獲取一些信息。我想在我的WKWebView中顯示這些信息並每秒更新一次。我正在使用本地HTML。如何將數據從swift發送到javascript並將它們顯示在我的Web視圖中?

我發現了一些例子,說明如何在本地代碼和JS之間進行通信,但沒有關於如何傳輸我的「本地」數據並將它們顯示在Web視圖中。 謝謝。

+0

您正在使用iOS或OS X嗎? –

+0

我正在使用iOS混合應用程序 – Lola

回答

6

您應該讓位置管理員爲您更新位置,而不是設置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> 

如果您在模擬器測試此,選擇調試>位置>市潤看它會不斷更新(就像你正在穿過公園一樣)。

+0

非常感謝您的幫助!它完美的作品:) – Lola

+1

只要確保JSON字符串不包含未轉義的換行符。 'evaluateJavaScript'將不起作用,除非換行符被轉義。 – Crashalot

+0

另外,在NSJSONSerialization中不要使用.prettyPrinted選項,按照上面的方法使用[],否則它也不起作用。 – TerryB

相關問題