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

I am trying to send a JSON object containing username and password info from an iOS app to my server for login. However, it seems like the php code never received the JSON object or decoded it correctly. I have tried many different ways to convert JSON object and send to server, but none of them succeeded. I am coding in swift 2 by the way. Any help? THANKS!

Here is my swift code:

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

And here is my php code:

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();
dp0518
dp0518 好的,我发现了问题。这是我无法写入文件的权限问题。我已将文件路径中所有父文件夹的模式更改为777.现在它可以写入文件。不管怎么说,还是要谢谢你!
4 年多之前 回复
doulan8330
doulan8330 我可以帮助你在php方面,但我不知道ios,所以-如果没有收到数据,我认为问题存在于ios脚本中。对不起。您还可以尝试写入文件变量,如$_REQUEST和$_POST($data=print_r($_REQUEST,True);,然后将$data写入文件)
4 年多之前 回复
dqtu14636
dqtu14636 我试图将$data写入文件而不对其进行解码,但文件中没有出现任何内容。
4 年多之前 回复
douzou7012
douzou7012 你有没有解码它打印$data?另外,你的$_POST值是对的吗?
4 年多之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐