swift3 webview与发布请求 [英] swift3 webview with post request

查看:92
本文介绍了swift3 webview与发布请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行一个学校项目,而我是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

在上面的帖子中,他正在使用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方法的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请求(例如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.)

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

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)

似乎不是很好的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆