用于发布json格式数据的API URL

时间:2019-03-18 17:29:23

标签: ios json swift api url

我如何将代码从文本字段传输到json格式的数据中。

以下是我当前拥有的代码,但是单击按钮时似乎没有将文本字段中的数据传输到json。在此代码中是否存在任何错误?

@IBAction func submitButton(_ sender: Any) {

    // parse in paramaters
    let parameters = ["Name": nameTextField, "Email": emailTextField, "DOB": dateTextField] as [String : Any]

    guard let url = URL(string: "https://prod-69.westeurope.logic.azure.com/workflows/d2ec580e6805459893e498d43f292462/triggers/manual/paths/invoke?api-version=2016-06-01&sp=%2Ftriggers%2Fmanual%2Frun&sv=1.0&sig=zn8yq-Xe3cOCDoRWTiLwDsUDXAwdGSNzxKL5OUHJPxo") else { return }
    var request = URLRequest(url: url)

    // let url session know that this is a post request
    request.httpMethod = "POST"
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")

    // convert paramaters to JSON
    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
    request.httpBody = httpBody

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }

        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error)
            }
        }
        }.resume()
}

1 个答案:

答案 0 :(得分:0)

类型为nameTextFieldemailTextField的{​​{1}},dateTextFieldString。确保您传递的是UITextField属性,而不是UITextField.text本身。

参见下文:

UITextField