Swift Webview Xcode Post Data

Swift webview xcode post data

You could use a Class like NSURLSession, which allows control over your HTTP interaction, and loads the HTML string in your webView

Usage example:

let request = NSMutableURLRequest(URL: NSURL(string: "http://www.someLink.com/postName.php"))
request.HTTPMethod = "POST"
let postString = "id=XYZ"
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in

if error != nil {
println("error=\(error)")
return
}

println("response = \(response)")

let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString = \(responseString)")
}
task.resume()

Or you can prepare an NSMutableURLRequest with a POST body and load that in your webView like so:

//need to use MutableRequest to set HTTPMethod to Post.
var url = NSURL(string: "http://www.somesite.com/post.php")
var request = NSMutableURLRequest(URL: url!)
request.HTTPMethod = "POST"
var bodyData: String = "someUsernameOrKey"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding)
webView.loadRequest(request)

swift3 webview with post request

Just create a URLRequest for POST as shown in the second link, and pass it to the webView:

var request = URLRequest(url: URL(string: "http://www.example.com/")!)
request.httpMethod = "POST"
let postString = "id=\(idString)"
request.httpBody = postString.data(using: .utf8)
webView.loadRequest(request) //if your `webView` is `UIWebView`

(Consider using WKWebView rather than UIWebView.)

You may need idString to be escaped if it contains some special characters.


By the way, the two line code:

let URL = NSURL(string: "https://www.example.com?data=\(passData)")
webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)

does not seem to be a good Swift 3 code. It can be written as:

let url = URL(string: "https://www.example.com?data=\(passData)")!
webView.loadRequest(URLRequest(url: url))

How can I obtain POST request body from WKWebView in Swift?

I'm answering my own question because I figured out how to do this on my own. Perhaps my question wasn't clear. My end goal was to extract the body content as a string.

Firstly, I ditched the callback I used:

func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: @escaping (WKNavigationResponsePolicy) -> Void) {
// do stuff
}

And instead, I used this callback and executed some javascript on the result:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
webView.evaluateJavaScript("document.getElementById(\"my-id\").innerHTML", completionHandler: { (jsonRaw: Any?, error: Error?) in
guard let jsonString = jsonRaw as? String else { return }
let json = JSON(parseJSON: jsonString)
// do stuff
})
}

The id "my-id" comes from the response I constructed on the back end of this service, just in case the web view wrapped any other HTML around my response. My original intention was to do this without having to run any javascript, but I guess there's no other way. This works pretty well anyway.

Loading a webpage through UIWebView with POST parameters

Create POST URLRequest and use it to fill webView

NSURL *url = [NSURL URLWithString: @"http://your_url.com"];
NSString *body = [NSString stringWithFormat: @"arg1=%@&arg2=%@", @"val1",@"val2"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];
[request setHTTPMethod: @"POST"];
[request setHTTPBody: [body dataUsingEncoding: NSUTF8StringEncoding]];
[webView loadRequest: request];


Related Topics



Leave a reply



Submit