简体   繁体   中英

Http post request from Swift to a php script

I have a php script name UserRegister.php. In this script I have some Post variables. These variable comes from my iOS app and then the script should save it to my mysql database.

my .php script

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();

my swift code

//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()

I print out my response and get status code: 500 and in my header it says Connection = close. And it doesn't return any of the JSON file to my iOS app.

You are retrieving the variables using PHP's $_POST command but sending them using a GET request in Swift. You can change the request type in Swift using request.HTTPMethod = "GET" or alternatively use $_GET in PHP.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM