2

Sorry For this my English is weak I try many types of a solution but not working in Xcode 11.2.1 and swift 5

I try this

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: "&")  
    } 

and this

Post Request with Parameter

And also try to add below lines in my code

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

But not Working I fire the Request because not working the WKWebView screen is Open but not Load request. If I not set navigationDelegate and open normal URL then it is working completely If I set navigationDelegate then blank page come in all Request Like Normal URL fire or post parameter URL fire, All are coming to Blank Page in I can't understand what is the Problem with WKWebView Please help me. Thanks in advance

Nikunj
  • 655
  • 3
  • 13
  • 25

3 Answers3

2

The request body uses the same format as the query string:

parameter=value&also=another

Therefore the content type of your request is of type 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)  
AbdelAli
  • 796
  • 1
  • 6
  • 6
1

I think we not need to use URLSession.dataTask, simply create URLRequest and declare your method + with stating header fields like this:

private final func postRequestToURL(_ urlString: String) {
            
    guard let url = URL(string: urlString) else {
        debugPrint("Error: Invailed URL!")
        return
    }
    
    var parameters = Parameters()
    parameters["name"] = "Example"
    parameters["surname"] = "ExmpleExample"
    parameters["timeZone"] = "MiddleEast/MENA"
    parameters["test"] = "YES"
            
    var urlRequest = URLRequest(url: url)
    urlRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
    urlRequest.allowsCellularAccess = true
    urlRequest.httpMethod = "POST"
    let postString = parameters.getPostString()
    urlRequest.httpBody = postString.data(using: .utf8)
    if let wkNavigation = self.webView.load(urlRequest) {
        debugPrint("Success: \(wkNavigation.description)")
    } else {
        debugPrint("Failure: Cannot load current request.")
    }
}

Here we can convert our parameters to String by this extension:

public extension Dictionary where Key == String, Value == Any {

   func getPostString() -> String {
      var data = [String]()
      for(key, value) in self {
          data.append(key + "=\(value)")
      }
      return data.map { String($0) }.joined(separator: "&")
   }
}

I am using this code over my commercial app.

Additional info: I allowed request eligible to run over cellular by marking allowsCellularAccess = true this is optional

Coder ACJHP
  • 1,940
  • 1
  • 20
  • 34
0

Try this, we will initiate a POST request using URLSession convert the data returned by the server to String and instead of loading the url we will use loadHTMLString which will:

Set the webpage contents and base URL.

and the content is our converted string::-

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()
iOS Developer
  • 464
  • 6
  • 24