title: Swift Headless WKWebView; running XMLHttpRequest
body: <p><strong>How can I run an XMLHttpRequest from within a WKWebView that I have created in Swift?</strong></p>
  
  <p>Currently, I use the WKWebView to access a page on a server I own. This page contains my Javascript. However, when I attempt to make an XMLHttpRequest by using WKWebView.evaluateJavaScript (i.e. call a javascript function that makes an XMLHttpRequest) the Javascript code executes successfully but the Safari debugger shows "Failed to load resource".</p>
  
  <p><em>However</em>, if I 'manually' make an XMLHttpRequest by using the console in the Safari debugger and <em>then</em> call my request function from my app, it works fine - but only once!</p>
  
  <p>I'm at a bit of a loss as to why this is...</p>
  
  <hr>
  
  <p>As mentioned in the comments, a better solution than bundling the Javascript with my swift library is to host the scripts on a page that is accessed via the WKWebView. Previous information maintained below;</p>
  
  <p><strike>Some background: I have been tasked with producing a Swift library that wraps our current Javascript API. I had hoped to use a WKWebView to simply load and execute our existing javascript code, however any XMLHttpRequests that I run simply return error (fire the onerror callback) instantly. The error object returned to onerror is <em>{"position":0,"totalSize":0}</em></p>
  
  <p><a href="https://stackoverflow.com/questions/26514090/wkwebview-does-not-run-javascriptxml-http-request-with-out-adding-a-parent-vie">This thread</a> seems to suggest that my WKWebView needs a 'parent' in order to execute javascript correctly. I have attempted to reproduce their code in Swift, but to no effect (see below)</p>
  
  <pre><code>let webConf = WKWebViewConfiguration()
  WKWebView webView = WKWebView(frame: CGRectZero, configuration: webConf)
  UIApplication.sharedApplication().keyWindow?.addSubview(webView)
  </code></pre>
  
  <p>In order to get to this point, I have had to set 'App Transport Security Settings -> Allow Arbitrary Loads' to 'YES' in my info.plist file, in order to enable non-https requests.</strike></p>