applecrusher
applecrusher

Reputation: 5648

Swift WKWebView: Can't find variable error when calling method

I am trying to pass GPS coordinates to a method call setIOSNativeAppLocation. I have the following code below but I am getting this error:

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})

I am not sure if it has something to do with the syntax or anything else. If someone knows what I am doing wrong I would greatly appreciate it.


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
         }

      }
   }
}

Upvotes: 5

Views: 7614

Answers (1)

Abhishek singh
Abhishek singh

Reputation: 415

I think this can help you out- The way we are passing parameter here.

we should put it in single quote('\(lat)', '\(lon)') else it will be like a variable.

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
     }
   }

 }

}

Upvotes: 2

Related Questions