将地理位置从 Swift 2 ViewController 传递到 Javascript 方法

Passing Geolocation from Swift 2 ViewController to Javascript Method

下面的代码能够获取地理位置并将其打印出来。我根据一些在线教程并查看 Swift 文档得到了这个。我想以字符串的形式将地理位置从 Swift 2 传递到 Javascript。我能够获取 GeoLocations,但我不知道如何将这些字符串传递到我在 Web 视图中的 Javascript 代码。

下面是我的代码:

@IBOutlet weak var Webview: UIWebView!

let locMgr = CLLocationManager()

override func viewDidLoad() {

    super.viewDidLoad()
    loadAddressURL()
    locMgr.desiredAccuracy = kCLLocationAccuracyBest
    locMgr.requestWhenInUseAuthorization()
    locMgr.startUpdatingLocation()
    locMgr.delegate = self //necessary



}

func locationManager(manager: CLLocationManager , didUpdateLocations locations: [CLLocation]){
    let myCurrentLoc = locations[locations.count-1]
    var myCurrentLocLat:String = "\(myCurrentLoc.coordinate.latitude)"
    var myCurrentLocLon:String = "\(myCurrentLoc.coordinate.longitude)"

    print(myCurrentLocLat)
    print(myCurrentLocLon)

    //pass to javascript here by calling setIOSNativeAppLocation

}

我的网站上有 javascript 使用此方法:

function setIOSNativeAppLocation(lat , lon){

  nativeAppLat = lat;
  nativeAppLon = lon;
  alert(nativeAppLat);
  alert(nativeAppLon);

}

我查看了另一个标有 的问题,解决方案如下:

func sendSomething(stringToSend : String) {
    appController?.evaluateInJavaScriptContext({ (context) -> Void in

       //Get a reference to the "myJSFunction" method that you've implemented in JavaScript
       let myJSFunction = evaluation.objectForKeyedSubscript("myJSFunction")

       //Call your JavaScript method with an array of arguments
       myJSFunction.callWithArguments([stringToSend])

       }, completion: { (evaluated) -> Void in
          print("we have completed: \(evaluated)")
    })
}

但是我没有 appDelegate,我想直接从这个视图进行这些更改。所以我得到一个 "use of unresolved identifier appDelegate".

您 link 的答案是针对 Apple TV 的,这与 iOS 和 UIWebView 非常不同。

在您尝试 运行 任何 javascript 之前,您需要确保网络视图已完成加载(参见 webViewDidFinishLoad)。

Web 视图准备就绪并且您拥有详细信息后,您可以创建一个 String,其中包含您要执行的 javascript,然后将其传递给 Web 视图:

let javaScript = "setIOSNativeAppLocation(\(myCurrentLoc.coordinate.latitude), \(myCurrentLoc.coordinate.longitude))"

webView.stringByEvaluatingJavaScriptFromString(javaScript)

您必须实现 UIWebview delegate.Javascript 函数应该在 webviewDidFinishLoad 之后调用。

override func viewDidLoad() {
     super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.
     let url = NSURL (string: URLSTRING);
     let requestObj = NSURLRequest(URL: url!);
webView.delegate = self
    webView.loadRequest(requestObj);
  }

    func webViewDidFinishLoad(webView: UIWebView) {
            let javaScriptStr = "setIOSNativeAppLocation(\(myCurrentLoc.coordinate.latitude), \(myCurrentLoc.coordinate.longitude))"

            webView.stringByEvaluatingJavaScriptFromString(javaScriptStr)
        }