Swift: How to wrap an async method in a synchronous method?
<p>I'm trying to load Javascript synchronously in my <code>WKWebView</code>. From my research it looks like the <code>evaluateJavaScript</code> method is asynchronous and this is causing errors because the page would load before the JS that overrides a lot of behavior (it only works a portion of the time because of the async nature).</p>

<p>I've tried this but it doesn't seem to work  :</p>

<pre><code>extension WKWebView {
  func evaluateJavaScriptSynchronously(script: String, completion: () -&gt; Void) {
    let semaphore = dispatch_semaphore_create(1)

    evaluateJavaScript(script) { (result, error) in
      if error == nil {
        if result != nil {
          print("SUCCESS")
          completion()
        }
      } else {
        print("ERROR!!!")
        print(error)
        print(result)
        completion()
      }
      dispatch_semaphore_signal(semaphore)
    }

    let timeout = dispatch_time_t(10000)
    dispatch_semaphore_wait(semaphore, timeout)
  }
}
</code></pre>

<p>I know it's not working because the page still sometimes loads as if the JS wasn't there. Is there a similar thing I can do to synchronize the process?</p>