ios - 如何在 WKWebView 中加载带有参数的 POST URLRequest?

标签 ios swift5 ios12 xcode11

抱歉,我的英语很弱 我尝试了多种类型的解决方案,但在 Xcode 11.2.1swift 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: "&")  
    } 

还有这个

Post Request with Parameter

并尝试在我的代码中添加以下行

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/

相关文章:

ios - 如何向所有 UIViewControllers 添加一个通用的 float 操作按钮

swift - "Implicitly unwrapped property"警告?

swift - carPlay 的新代表

swift - 对成员 'buildBlock()' 的模糊引用

ios - 此iPhone运行的是iOS 12.0(16A366),此版本的Xcode可能不支持

ios - 弹出窗口不会请求在 iOS 12 中访问相机的权限

ios - Swift CIfilter 从 collectionView 中选择

iphone - 旋转后重新定位UIWindow

ios - swift 错误 : "MailCompositionService quit unexpectedly"

ios - idleTimerDisabled 不适用于(自主)单一应用程序模式