我如何将代码从文本字段传输到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()
}
答案 0 :(得分:0)
类型为nameTextField
或emailTextField
的{{1}},dateTextField
和String
。确保您传递的是UITextField
属性,而不是UITextField.text
本身。
参见下文:
UITextField