How to send form data in POST request in Swift 3

2019-01-28 13:15发布

问题:

I am trying to post form-data using webservice, userName & password, but in response it's showing an error stating "Could not connect to the server.".

Please help me to send form data in the POST request.

        let dict:[String:String] = ["userName": userName as! String, "password": password as! String]

        do {

            let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)

            let url = URL(string: "(some url)")!

            var request  = URLRequest(url: url)

            request.httpMethod = "POST"

            request.setValue("application/x-www-form-urlencoded charset=utf-8", forHTTPHeaderField: "Content-Type")

            request.httpBody = jsonData

            let task = URLSession.shared.dataTask(with: request) { data, response, error in

                if error != nil {

                    print(error!.localizedDescription)

                    return

                }

                do {

                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary

                    if let parseJSON = json {

                        let resultValue:String = parseJSON["success"] as! String;

                        print("result: \(resultValue)")

                        print(parseJSON)

                    }

                } catch let error as NSError {

                    print(error)

                }
            }

            task.resume()

        } catch {

            print(error.localizedDescription)

        }

I've tried adding values in the request, may be some values are missing in the request formed. Please help!

Thats the POSTMAN response

回答1:

my calling api class

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

    static func callPost(url:URL, params:[String:Any], finish: @escaping ((message:String, data:Data?)) -> Void)
    {
        var request = URLRequest(url: url)
        request.httpMethod = "POST"

        let postString = self.getPostString(params: params)
        request.httpBody = postString.data(using: .utf8)

        var result:(message:String, data:Data?) = (message: "Fail", data: nil)
        let task = URLSession.shared.dataTask(with: request) { data, response, error in

            if(error != nil)
            {
                result.message = "Fail Error not null : \(error.debugDescription)"
            }
            else
            {
                result.message = "Success"
                result.data = data
            }

            finish(result)
        }
        task.resume()
    }
}

and when use it

ApiService.callPost(url: url, params: params, finish: finishPost)

and the finish function

func finishPost (message:String, data:Data?) -> Void
{
    do
    {
        if let jsonData = data
        {
            let parsedData = try JSONDecoder().decode(Response.self, from: jsonData)
            print(parsedData)
        }
    }
    catch
    {
        print("Parse Error: \(error)")
    }
}