为什么我的服务器php代码无法从我的iOS应用程序接收JSON对象?

时间:2016-02-15 23:06:26

标签: php ios json

我正在尝试将包含用户名和密码信息的JSON对象从iOS应用程序发送到我的服务器进行登录。但是,似乎php代码从未收到JSON对象或正确解码。我已经尝试了许多不同的方法来转换JSON对象并发送到服务器,但没有一个成功。顺便说一句,我在swift 2编码。有帮助吗?谢谢!

这是我的快捷代码:

let myUrl = NSURL(string: "myURL");
let request = NSMutableURLRequest(URL: myUrl!);
request.HTTPMethod = "POST";

let params : [String : AnyObject] = ["username": username!, "password": password!];
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type");

do {
   let jsonData = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions());
    request.HTTPBody = jsonData;
    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding)! as String
    print(jsonString);
    print(request.HTTPBody);

} catch {
    print(error)
}

let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in

    do{
        let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as? NSDictionary

        print(response)
        if let parseJSON = json {
            let resultValue = parseJSON["type"] as? Int
            print("result: \(resultValue)")
        }
    } catch {
        print(error)
    }
})

task.resume()

这是我的PHP代码:

require("Conn.php");
require("MySQLDao.php");

$fp = fopen("data.txt", "a+");

$data = file_get_contents('php://input');
$json = json_decode($data, false);
$username = $_POST['username'];
$password = $_POST['password'];

fwrite($fp, $data);
fwrite($fp, $json);
fwrite($fp, $username);
fwrite($fp, $password);
fclose($fp);
$returnValue = array();

if (empty($username) || empty($password)) {
    $returnValue["status"] = "error";
    $returnValue["message"] = "Missing required field";
    echo json_encode($returnValue);
    return;
}  

$dao = new MySQLDao();
$dao->openConnection();
$userType = $dao->passwordAuthentification($username, $password);

if ($userType != null) {
    $returnValue["type"] = (int)$userType;
    echo json_encode($returnValue);
} else {
    $returnValue["type"] = -1;
    $returnValue["message"] = "user is not found";
    echo json_encode($returnValue);
}

$dao->closeConnection();

0 个答案:

没有答案