如何在 Swift 3 中发送 POST 请求中的表单数据

How to send form data in POST request in Swift 3

我正在尝试使用网络服务、用户名和密码 post 表单数据,但作为响应,它显示了一个错误 "Could not connect to the server."。

请帮我在POST请求中发送表单数据。

        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)

        }

我试过在请求中添加值,可能是形成的请求中缺少一些值。请帮忙!

Thats the POSTMAN response

我的电话apiclass

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([=10=]) }.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()
    }
}

以及何时使用它

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

和结束函数

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