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

app*_*her 5 swift wkwebview swift3

我正在尝试将 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})
Run Code Online (Sandbox Code Playgroud)

我不确定它是否与语法或其他任何东西有关。如果有人知道我做错了什么,我将不胜感激。


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
         }

      }
   }
}
Run Code Online (Sandbox Code Playgroud)

Abh*_*ngh 2

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

我们应该把它放在单引号中('\(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
     }
   }

 }

}
Run Code Online (Sandbox Code Playgroud)