使用NSURLSession的帖子请求不返回任何帖子数据

时间:2015-05-28 09:38:43

标签: ios swift nsurlsession

我正在尝试向我的基于PHP的服务发送HTTP请求。

点击按钮我的代码是:

@IBAction func clickForRequest(sender: AnyObject) {

    let myUrl = NSURL(string: "http://localhost/app");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";

    // Compose a query string
    let postString = "firstName=James&lastName=Bond";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil
        {
            println("error=\(error)")
            return
        }

        // You can print out response object
        println("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("responseString = \(responseString)")

        //Let's convert response sent from a server side script to a NSDictionary object:

        var err: NSError?
        var myJSON = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error:&err) as? NSDictionary

        if let parseJSON = myJSON {
            // Now we can access value of First Name by its key
            var firstNameValue = parseJSON["firstName"] as? String
            println("firstNameValue: \(firstNameValue)")
        }

    }

    task.resume()

}

我的PHP代码是:

<?php

echo "<pre>";
print_r($_POST);
echo "</pre>";

?>

但我得到的ResponseString只是一个空数组:

Array( )

感谢。

1 个答案:

答案 0 :(得分:1)

我认为问题在于您的PHP代码段不会输出有效的JSON,而这正是您尝试反序列化的内容。

试试这个

<?php
exit(json_encode($_POST));
?>