我是Swift 4编程的新手。这是我的第一个iOS项目。我在使用JSON将数据发送到服务器时遇到了困难!
服务器正在接收所有参数textfields为空。
let pram = ["departement": departmentTextField.text, "fname": firstNameTextField.text, "lname": lastNameTextField.text, "email": emailTextField.text, "mbl": mobileNumberTextField.text, "address": residentialTextField.text,"subrub": suburbTextField.text,"dob": chooseDateofBTextField.text,"gender": genderTextField.text, "cardno": medicareCardNoTextField.text, "edate": medicareExpiryTextField.text, "source": howDidText.text, "condition": conditionTextField.text, "appdate": aptDOPTextField.text]
let url = URL(string: "//myAPI")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = pram
request.httpBody = (postString as AnyObject).data
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else { // check for fundamental networking error
print("error=\(error)")
let alert = UIAlertController(title: "Connection Lost ", message: "Please Try Again Later", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(response)")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(responseString)")
let alert = UIAlertController(title: "Your Appointement has been placed", message: "", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Done", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
task.resume()
答案 0 :(得分:0)
我建议您使用Almofire。这是一个非常简单的围兜。您可以轻松地使用它来发送服务器请求:
let parameters: Parameters = ["departement": departmentTextField.text!] //and so on
Alamofire.request("apiPath", method: .post, parameters: parameters).responseJSON { response in
if let json = response.result.value {
print("JSON: \(json)") // serialized json response
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Data: \(utf8Text)") // original server data as UTF8 string
}
}
根据你的问题,你必须插入一个"!"在textfield的文本之后。
以下是almofire文档:https://github.com/Alamofire/Alamofire/blob/master/Documentation/Usage.md#making-a-request