Http从Swift发送请求到PHP脚本

时间:2015-09-15 21:05:23

标签: php ios mysql swift http-post

我有一个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应用程序。

1 个答案:

答案 0 :(得分:0)

您正在使用PHP的$_POST命令检索变量,但是在Swift中使用GET请求发送它们。您可以使用request.HTTPMethod = "GET"在Swift中更改请求类型,或者在PHP中使用$_GET