Alamofire .POST response JSON nil using PHP-open source projects Alamofire/Alamofire
How can I get JSON values back from my PHP script?
I get nil
in my JSON response.
The Alamofire.request
works. (i.e. I receive JSON data at my PHP script.)
The PHP script works. (i.e. I can process the input JSON and I generate a valid JSON string using json_encode
.)
Here’s the code…
Swift:
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 Results:
request: { URL: http://www.myserver/from_swift.php }
response: Optional( { 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:
Solution: I had an error in my PHP script. As a result, the error message was being passed back in the response before the JSON string. As a result, the .responseJSON
correctly didn’t recognize the data as JSON.
To help others, when you’re getting nil
in your data parameter from .responseJSON
, troubleshoot by changing .responseJSON
to .responseString
to see if you get any results back in the data parameter. For example, when I changed to .responseString
I saw the following:
JSON: Optional("
\nStrict Standards: 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 /home/xxx/public_html/from_swift.php on line 115
\n{\"books\":[\"the hunger games\",\"mockingjay\"]}")
Notice, the error message in front of the json string. After I corrected the PHP script and changed back to .responseJSON
, it worked…