带有发布请求的swift3 webview [英] swift3 webview with post request
问题描述
我正在运行一个学校项目,我是 swift3 的新手.
I am running a school project and I am new from swift3.
通过搜索,我知道如何将数据从一个视图传递到另一个视图:将数据从 tableview 传递到 webview
By searching, I know how to pass a data from one view to anther: Passing data from a tableview to webview
在上面的帖子中,他使用http get请求将数据传递到网站,然后重新加载webivew:
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)
我在这里看到了一些有用的链接,比如关于带有 http post 请求的代码:使用 POST 方法在 Swift 中的 HTTP 请求.结果,代码可以打印出http响应.
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.
我的问题是,如何通过发送 http post reuqest(如 id、name 等)而不是 get 方法来实现 webview.
My question is that, how to implement a webview with sending a http post reuqest, like id, name, etc, instead of get method.
换句话说:我想重新加载 webview(如 example.com),该网站将包含我通过 http post 请求发送的值.
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:
example.com:
$id = $_POST['id'];
echo $id;
谢谢.
推荐答案
只需为 POST 创建一个 URLRequest
如第二个链接所示,并将其传递给 webView
:
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`
(考虑使用 WKWebView
而不是 UIWebView
.)
(Consider using WKWebView
rather than UIWebView
.)
如果 idString
包含一些特殊字符,您可能需要对其进行转义.
You may need idString
to be escaped if it contains some special characters.
顺便说一下两行代码:
let URL = NSURL(string: "https://www.example.com?data=(passData)")
webView.loadRequest(NSURLRequest(url: URL! as URL) as URLRequest)
似乎不是一个好的 Swift 3 代码.可以写成:
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))
这篇关于带有发布请求的swift3 webview的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!