Search code examples
phpjsonapiswift3alamofire

Sending JSON data in the body of Alamofire Request


I'm trying to make an api call to submit some data using Alamofire (version 4.0). I think the request has succeed. But the trouble i'm having is that when making the call I get a response from the server that 0 byte FAILURE.

I have tried many of the solutions currently on StackOverflow and cannot find a solution. Thanks for your help.

Here is my Postman setup:

enter image description here

My Swift code:

import UIKit
import Alamofire

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let headers: HTTPHeaders = [ "content-type": "x-www-form-urlencoded"]


        Alamofire.request("myurl.php?method=GET_RECENT", headers: headers).responseJSON { response in
            debugPrint(response)
            print(response.request)  // original URL request
            print(response.response) // HTTP URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization

            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
        }

    }
}

The error I'm getting is:

[Request]: myurl.php?method=GET_RECENT [Response]: { URL: myurl.php?method=GET_RECENT } { status code: 200, headers { "Cache-Control" = "max-age=0"; Connection = "Keep-Alive"; "Content-Length" = 0; "Content-Type" = "text/html; charset=UTF-8"; Date = "Sun, 01 Jan 2017 11:41:31 GMT"; Expires = "Sun, 01 Jan 2017 11:41:31 GMT"; "Keep-Alive" = "timeout=7, max=100"; Server = "Apache/2.2.15 (CentOS)"; "X-Powered-By" = "PHP/5.6.25"; } } [Data]: 0 bytes [Result]: FAILURE: responseSerializationFailed(Alamofire.AFError.ResponseSerializationFailureReason.inputDataNilOrZeroLength) [Timeline]: Timeline: { "Request Start Time": 504963459.698, "Initial Response Time": 504963459.821, "Request Completed Time": 504963459.821, "Serialization Completed Time": 504963459.821, "Latency": 0.123 secs, "Request Duration": 0.123 secs, "Serialization Duration": 0.001 secs, "Total Duration": 0.124 secs } Optional(myurl.php?method=GET_RECENT) Optional( { URL: myurl.php?method=GET_RECENT } { status code: 200, headers { "Cache-Control" = "max-age=0"; Connection = "Keep-Alive"; "Content-Length" = 0; "Content-Type" = "text/html; charset=UTF-8"; Date = "Sun, 01 Jan 2017 11:41:31 GMT"; Expires = "Sun, 01 Jan 2017 11:41:31 GMT"; "Keep-Alive" = "timeout=7, max=100"; Server = "Apache/2.2.15 (CentOS)"; "X-Powered-By" = "PHP/5.6.25"; } }) Optional(0 bytes) FAILURE


Solution

  • I think you are setting your Postman setup is invalid. To send JSON as data in your GET request your should be using raw options, like on the picture below.

    enter image description here