抱歉,我的英语很弱
我尝试了多种类型的解决方案,但在 Xcode 11.2.1
和 swift 5
我试试这个
var urlRequest = URLRequest(url: URL(string: "https://xxxxxx/login")!)
urlRequest.httpMethod = "POST"
let params = [
"username": SessionManager.shared.username!,
"password": SessionManager.shared.password!,
"vhost": "standard"
]
let postString = self.getPostString(params: params)
urlRequest.httpBody = postString.data(using: .utf8)
webView.load(urlRequest)
...
//helper method to build url form request
func getPostString(params:[String:String]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
还有这个
并尝试在我的代码中添加以下行
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
但不工作
我触发请求是因为 WKWebView
屏幕不工作,打开但未加载请求。
如果我没有设置 navigationDelegate 并打开正常的 URL
那么它可以完全工作
如果我设置了navigationDelegate,那么所有请求中都会出现空白页面,就像普通URL
火或发布参数URL
火一样,所有内容都将进入空白页面
我不明白 WKWebView
的问题是什么
请帮我。
提前致谢
最佳答案
请求正文使用与查询字符串相同的格式:
parameter=value&also=another
因此您的请求的内容类型为 application/x-www-form-urlencoded 类型:
let postString = self.getPostString(params: params)
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "POST"
urlRequest.httpBody = postString.data(using: .utf8)
webView.load(urlRequest)
关于ios - 如何在 WKWebView 中加载带有参数的 POST URLRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60538973/