Alamofire .POST响应JSON nil使用PHP

时间:2015-01-16 12:12:49

标签: php json post response alamofire

如何从PHP脚本中获取JSON值?

我在JSON响应中得到nil

Alamofire.request有效。 (即我在PHP脚本中收到JSON数据。)

PHP脚本有效。 (即我可以处理输入JSON,并使用json_encode生成有效的JSON字符串。)

这是代码......

夫特:

Alamofire
    .request(.POST, "http://www.myserver.com/from_swift.php", parameters: dicMyDictionary, encoding: ParameterEncoding.JSON)
    .responseJSON {
        (request, response, JSON, error) in
        println("request: \(request)")
        println("response: \(response)")
        println("JSON: \(JSON)")
        println("error: \(error)")
}

Println结果:

request: <NSMutableURLRequest: 0x7ff3b242de90> { URL: http://www.myserver/from_swift.php }

response: Optional(<NSHTTPURLResponse: 0x7ff3b2776c40> { URL: http://www.myserver/from_swift.php } { status code: 200, headers {
    Connection = "Keep-Alive";
    "Content-Type" = "application/json";
    Date = "Fri, 16 Jan 2015 12:02:24 GMT";
    "Keep-Alive" = "timeout=5, max=200";
    Server = "Apache/2.2.29 (Unix)";
    "Transfer-Encoding" = Identity;
    "X-Powered-By" = "PHP/5.4.36";
} })

JSON: nil

error: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x7ff3b380db80 {NSDebugDescription=Invalid value around character 0.})

PHP:

<?php
    header('Content-Type: application/json');
    ... More code here ...
    echo json_encode($aryOfStrings);
?>

解决方案: 我的PHP脚本出错了。因此,错误消息在JSON字符串之前的响应中传回。因此,.responseJSON正确地无法将数据识别为JSON。

要帮助其他人,当您从nil获取.responseJSON数据参数时,可以通过将.responseJSON更改为.responseString进行排查,看看您是否收到任何结果在data参数中。例如,当我更改为.responseString时,我看到了以下内容:

JSON: Optional("<br />\n<b>Strict Standards</b>:  mysqli::next_result(): There is no next result set. Please, call mysqli_more_results()/mysqli::more_results() to check whether to call this function/method in <b>/home/xxx/public_html/from_swift.php</b> on line <b>115</b><br />\n{\"books\":[\"the hunger games\",\"mockingjay\"]}")

注意,json字符串前面的错误消息。在我更正PHP脚本并更改回.responseJSON之后,它工作了......

0 个答案:

没有答案