2

抱歉,我的英语很弱,我尝试了多种类型的解决方案,但无法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,那么它完全可以 工作帮我。提前致谢URLURLWKWebView

4

2 回答 2

2

请求正文使用与查询字符串相同的格式:

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)  
于 2020-03-26T16:46:53.597 回答
0

试试这个,我们将使用 URLSession 发起一个 POST 请求,将服务器返回的数据转换为字符串,而不是加载 url,我们将使用 loadHTMLString 它将:

设置网页内容和基本 URL。

内容是我们转换后的字符串::-

var request = URLRequest(url: URL(string: "http://www.yourWebsite")!)
    request.httpMethod = "POST"
    let params = "Your Parameters"
    request.httpBody = params.data(using: .utf8)

    let task = URLSession.shared.dataTask(with: request) { (data : Data?, response : URLResponse?, error : Error?) in
            if data != nil {
                if let returnString = String(data: data!, encoding: .utf8) {
                    self.webView.loadHTMLString(returnString, baseURL: URL(string: "http://www.yourWebsite.com")!)
                }
            }
    }
    task.resume()
于 2020-03-05T06:18:18.537 回答