[英]Http post request from Swift to a php script
我有一个PHP脚本名称UserRegister.php。 在此脚本中,我有一些Post变量。 这些变量来自我的iOS应用程序,然后脚本应将其保存到我的mysql数据库中。
我的.php脚本
require("Conn.php");
require("MySQLDao.php");
$name=htmlentities($_POST["name"]);
$email=htmlentities($_POST["email"]);
$password=htmlentities($_POST["password"]);
$returnValue = array();
if(empty($email) || empty($password))
{
$returnValue["status"] = "error";
$returnValue["message"] = "Missing required field";
echo json_encode($returnValue);
return;
}
$dao = new MySQLDao();
$dao->openConnection();
$userDetails = $dao->getUserDetails($email);
if(!empty($userDetails))
{
$returnValue["status"] = "error";
$returnValue["message"] = "User already exists";
echo json_encode($returnValue);
return;
}
$secure_password = md5($password);
$result = $dao->registerUser($name, $email, $secure_password);
if($result)
{
$returnValue["status"] = "Success";
$returnValue["message"] = "User is registered";
echo json_encode($returnValue);
return;
}
$dao->closeConnection();
我的快速代码
//Store data
//Send user data to server side
let myURL: NSURL! = NSURL(string: "http://localhost:8888/iOSDatabase/UserRegister.php")
let request: NSMutableURLRequest = NSMutableURLRequest(URL: myURL!)
request.HTTPMethod = "POST"
let postString = "name=" + UserName + "&email=" + UserEmail + "&password=" + UserPassword
println(postString)
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
println("response =\(response)")
if error != nil {
println("error=\(error)")
return
}
var responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
println("responseString =\(responseString)")
var err: NSError?
if var json: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers, error: &err) as? NSDictionary {
if error == nil
{
println(json)
}
}
}
task.resume()
我打印出响应并得到状态代码:500,并且在标题中显示Connection = close。 而且它不会将任何JSON文件返回到我的iOS应用。
您正在使用PHP的$_POST
命令检索变量,但在Swift中使用GET请求发送变量。 您可以使用request.HTTPMethod = "GET"
在Swift中更改请求类型,或者在PHP中使用$_GET
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.