php - 从 Swift 到 php 脚本的 Http post 请求

标签 php ios mysql swift http-post

我有一个名为 UserRegister.php 的 php 脚本。在这个脚本中我有一些 Post 变量。这些变量来 self 的 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,并且在我的 header 中显示“Connection = close”。并且它不会将任何 JSON 文件返回到我的 iOS 应用程序。

最佳答案

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

关于php - 从 Swift 到 php 脚本的 Http post 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32595623/

相关文章:

php - Laravel 5.5。和 PHP 7

iOS swift Facebook AccountKit 自定义

ios - 替换 Swift 3 中的 enumerateSubstringsInRange

mysql - 在 MySQL 表之间移动行

mysql - 关于重复 key 更新 - 优先级

php - 加入其他表的数据透视表

php - 将 MySQL 数据从不同表传输到 CSV 文件

php - 错误500,与php建立MYSQL连接

ios - 为什么不将值user.username传递给导航器

mysql - 如何交换两个表都已创建的表名?