dongyimo1293 2016-02-15 23:06
浏览 80

为什么我的服务器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();
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 安装svn网络有问题怎么办
    • ¥15 Python爬取指定微博话题下的内容,保存为txt
    • ¥15 vue2登录调用后端接口如何实现
    • ¥65 永磁型步进电机PID算法
    • ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?
    • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
    • ¥15 如何处理复杂数据表格的除法运算
    • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
    • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
    • ¥15 latex怎么处理论文引理引用参考文献