swift POST请求不向服务器发送数据

时间:2016-07-10 14:33:20

标签: ios swift nsurl nsjsonserialization

从我在iphone应用程序中的登录视图中,我获得了用户名和密码,我想将其发送到服务器。我做了简单的脚本只是为了检查我的POST请求的功能是否有效。我没有任何错误,但似乎我的脚本得到空的POST变量。这是我的函数,用于将参数发送到我的php服务器脚本:

func postDataToURL() {

    let json = [ "username" : "vanja", "password" : "dinamo", "iphone" : "1" ]

    print (json)

    do {
            let jsonData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)

            // create post request
            let url = NSURL(string: "http://www.pnc.hr/rfid/login.php")!
            let request = NSMutableURLRequest(URL: url)
            request.HTTPMethod = "POST"

            // insert json data to the request
            request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
            request.HTTPBody = jsonData
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")


            let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
                if error != nil{
                    print("Error 55 -> \(error)")
                    return
                }

                do {
                    let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]

                    print("Result 34 -> \(result)")

                } catch {
                    print("Error  43-> \(error)")
                }
            }

            task.resume()
        }
        catch {
            //handle error. Probably return or mark function as throws
            print(error)
            return
        }
}

这是我的php脚本:

<?php 
if (isset($_POST['username']))
    $username = $_POST['username'];
else $username = "nista";

if (isset($_POST['password']))
    $password = $_POST['password'];
else $password = "nista";

if (isset($_POST['iphone']))
    $iphone = $_POST['iphone'];
else $iphone = "nista";

$arr = array('username' => $username, 'password' => $password, 'loggedIn' => 1, 'token' => 'ldsakj832WE32', 'iphone' => $iphone );
echo json_encode($arr);

&GT;

问题是脚本没有得到任何POST变量。

1 个答案:

答案 0 :(得分:1)

问题是:从Swift我发送了json文件,而不是POST变量。所以我不用$ _POST从php获取变量。我需要获取json文件并对其进行编码:

$json = file_get_contents('php://input');
//echo $json shoulkd show the json string

$array = json_decode($json, true);
// var_dump($arr) should show the array structure

$username = $array['username'];
$password = $array['password'];
$iphone = $array['iphone'];