Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift3 webview with post request

Tags:

swift3

I am running a school project and I am new from swift3.

By searching, I know how to pass a data from one view to anther: Passing data from a tableview to webview

In the post above, he is using http get request to pass data to website, then reload the webivew:

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

I see some useful links like about code with http post request in here: HTTP Request in Swift with POST method. In a result, the code can print out the http response.

My question is that, how to implement a webview with sending a http post reuqest, like id, name, etc, instead of get method.

In anther words: I want to reload the webview(like example.com) and that website will contain the value I sent via http post request.

example.com:

$id = $_POST['id'];
echo $id;

Thanks.

like image 675
Tom2132123 Avatar asked Dec 19 '22 10:12

Tom2132123


1 Answers

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))
like image 104
OOPer Avatar answered Mar 08 '23 06:03

OOPer