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

时间:2017-04-19 09:46:36

标签: post swift3 ios10 content-type form-data

我正在尝试使用webservice,userName&发布表单数据。密码,但作为响应,它显示错误,指出“无法连接到服务器。”。

请帮我在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

1 个答案:

答案 0 :(得分:14)

我的呼叫api课程

validNumericDirective

并在使用时

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

和完成功能

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