嗨,我是IOS App开发的新手。 我的代码是
func sendRequest<T: Decodable>(api: String, parameters: [String: String]? = nil, outputBlock: @escaping (T) -> () ) {
guard let url = URL(string: "http://xxyyzz.com/appRegister.php") else {return}
print("hitting : -", url.absoluteString)
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let newparam = ["name": "rr", "pass": "123456", "email": "rr@rr.com", "passConfirm":"123456"]
let httpBody = try? JSONSerialization.data(withJSONObject: newparam)
request.httpBody = httpBody
if let data = request.httpBody, let str = String(data: data, encoding: String.Encoding.utf8) {
print(str)
}
URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
DispatchQueue.main.async {
Indicator.shared.hideProgressView()
if let err = error {
print(err.localizedDescription)
return
}
guard let data = data else {return}
do {
let obj = String(data: data, encoding: String.Encoding.utf8)
print(obj ?? "oberrrrr")
}
}
}.resume()
}
和根据代码显示的控制台打印结果
击中:-http://xxyyzz.com/appRegister.php {“ email”:“ rr@rr.com”,“ passConfirm”:“ 123456”,“ name”:“ rr”,“ pass”:“ 123456”}
{“错误”:“请输入所有字段。”}
URL和参数在邮递员上效果很好,这意味着我的代码中缺少它们。
答案 0 :(得分:0)
仅在其他人遇到此问题时才回答问题。 这段代码很好,但是问题出在php web服务上,因为后端开发人员不接受json值作为参数,而是需要发送表单数据。 因此,可以在此处进行两种类型的修复
通过添加:-
在后端接受json$ postdata = file_get_contents(“ php:// input”); $ request = json_decode($ postdata,true);
发送表单数据而不是json
-PassThru -AsCustomObject -Force
}