Swift WKWebView:调用方法时找不到变量错误

时间:2016-09-30 21:16:34

标签: swift swift3 wkwebview

我正在尝试将GPS坐标传递给方法调用setIOSNativeAppLocation。我在下面有以下代码,但我收到此错误:

A JavaScript exception occurred" 
UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=
ReferenceError:
Can't find variable: setIOSNativeAppLocation, WKJavaScriptExceptionSourceURL=
http://mywebsite.com, NSLocalizedDescription=
A JavaScript exception occurred, WKJavaScriptExceptionColumnNumber=24})

我不确定它是否与语法或其他任何内容有关。如果有人知道我做错了什么,我会非常感激。

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {



   if(myCurrentLoc != nil){


      let lat = myCurrentLoc.coordinate.latitude
      let lon = myCurrentLoc.coordinate.longitude


      print(lat);
      print(lon);

      webView.evaluateJavaScript("setIOSNativeAppLocation(\(lat), \(lon));")  { (result, error) in
         guard error == nil else {
            print("there was an error")
            print(error)
            return
         }

      }
   }
}

1 个答案:

答案 0 :(得分:0)

我认为这可以为您提供帮助-我们在此处传递参数的方式。

我们应该将其放在单引号中('\(lat)','\(lon)'),否则它将像变量一样。

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { 
if(myCurrentLoc != nil){


  let lat = myCurrentLoc.coordinate.latitude
  let lon = myCurrentLoc.coordinate.longitude


  print(lat);
  print(lon);

  webView.evaluateJavaScript("setIOSNativeAppLocation('\(lat)', '\(lon)');")  { (result, error) in
     guard error == nil else {
        print("there was an error")
        print(error)
        return
     }
   }

 }

}