带有帖子请求的swift3 webview

时间:2016-12-31 14:36:13

标签: swift3

我正在运行一个学校项目,我是swift3的新手。

通过搜索,我知道如何将数据从一个视图传递给另一个视图: Passing data from a tableview to webview

在上面的帖子中,他正在使用http get request将数据传递到网站,然后重新加载webivew:

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

我在这里看到一些有用的链接,例如关于http post请求的代码: HTTP Request in Swift with POST method。结果,代码可以打印出http响应。

我的问题是,如何通过发送http post reuqest来实现webview,比如id,name等,而不是get方法。

换句话说:我想重新加载webview(如example.com),该网站将包含我通过http post请求发送的值。

example.com:

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

感谢。

1 个答案:

答案 0 :(得分:7)

只需为POST创建一个URLRequest,如第二个链接所示,并将其传递给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。)

如果它包含一些特殊字符,则可能需要转义idString

顺便说一句,两行代码:

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

似乎不是一个好的Swift 3代码。它可以写成:

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