我的应用程序遇到了问题,我正在尝试做的是通过"NSMutableURLRequest"URL将文本字段中的一些信息发送到我拥有的PHP文件。
错误说我的每个变量都有未定义的索引。
这是我第一次做这种练习,所以我不知道错误是在我的PHP代码中还是在Swift函数中。
下面是我的快速功能。
@IBAction func enviarInfo(_ sender: Any) {
let request = NSMutableURLRequest(url: NSURL(string: "http://www.mydomain/index.php")! as URL)
request.httpMethod = "POST"
//The String with the vars that will be sent to the $_POST["var"]
let postString = "nombre = (nombreText.text!) &aPaterno = (apaternoText.text!) &aMaterno = (amaternoText.text!) &genero = (genero.text!) &email = (emailText.text!) &telefono = (telefonoText.text!)"
request.httpBody = postString.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=(String(describing: error))")
return
}
print("response = (String(describing: response))")
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = (String(describing: responseString))")
}
task.resume()
}
PHP 代码如下所示
$nombre = $_POST["nombre"];
//All the $vars look like this.
echo $nombre;
我将不胜感激:)
您需要
从postString
中删除空格。
改变:
let postString = "nombre = (nombreText.text!) &aPaterno = ..."
自
let postString = "nombre=(nombreText.text!)&aPaterno=..." ...and so on
当发送这样的数据时,这些额外的空格在解析字符串时很重要。