HTTP Request in Swift with POST method

前端 未结 7 1016
名媛妹妹
名媛妹妹 2020-11-22 05:46

I\'m trying to run a HTTP Request in Swift, to POST 2 parameters to a URL.

Example:

Link: www.thisismylink.com/postName.php

Params:

7条回答
  •  心在旅途
    2020-11-22 06:19

    All the answers here use JSON objects. This gave us problems with the $this->input->post() methods of our Codeigniter controllers. The CI_Controller cannot read JSON directly. We used this method to do it WITHOUT JSON

    func postRequest() {
        // Create url object
        guard let url = URL(string: yourURL) else {return}
    
        // Create the session object
        let session = URLSession.shared
    
        // Create the URLRequest object using the url object
        var request = URLRequest(url: url)
    
        // Set the request method. Important Do not set any other headers, like Content-Type
        request.httpMethod = "POST" //set http method as POST
    
        // Set parameters here. Replace with your own.
        let postData = "param1_id=param1_value¶m2_id=param2_value".data(using: .utf8)
        request.httpBody = postData
    
        // Create a task using the session object, to run and return completion handler
        let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
        guard error == nil else {
            print(error?.localizedDescription ?? "Response Error")
            return
        }
        guard let serverData = data else {
            print("server data error")
            return
        }
        do {
            if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
                print("Response: \(requestJson)")
            }
        } catch let responseError {
            print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
            let message = String(bytes: serverData, encoding: .ascii)
            print(message as Any)
        }
    
        // Run the task
        webTask.resume()
    }
    

    Now your CI_Controller will be able to get param1 and param2 using $this->input->post('param1') and $this->input->post('param2')

提交回复
热议问题