I want to do a POST request to my WKWebView
but the headers doesn\'t get set when I monitor the requests with Charles so the request fails. What is wrong here?<
As the OP stated, I have also confirmed in Charles that the body is 0 bytes after webView.load(request)
.
There's a workaround for this WKWebView
bug, we will initiate a POST
request using URLSession convert the data returned by the server to String
and instead of loading the url we will use loadHTMLString which will:
Set the webpage contents and base URL.
and the content is our converted string:
var request = URLRequest(url: URL(string: "http://www.yourWebsite")!)
request.httpMethod = "POST"
let params = "do=something&andAgain=something"
request.httpBody = params.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
if data != nil {
if let returnString = String(data: data!, encoding: .utf8) {
self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourWebsite.com")!)
}
}
}
task.resume()