Search code examples
iosswiftalamofire

Empty request body in swift


I'm having issues sending a post request to my api. Both my iphone and my computer are on the same network, so I access the api the local public ip In my app I set the App transport security to allow arbitrary urls. The issue is the body is always empty. I tried creating a localtunnel so I can access it via https but the body is till empty.

Here is my call

import UIKit
import Alamofire

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        let parameters: Parameters = [
            "foo": "bar",
            "baz": ["a", 1],
            "qux": [
                "x": 1,
                "y": 2,
                "z": 3
            ]
        ]
        let headers: HTTPHeaders = [
            "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
            "Accept": "application/json"
        ]
        Alamofire.request("my-url", method: .post, parameters: parameters, headers: headers  ).responseJSON { (response) in
            debugPrint(response.result)
        }            
    }


}

Any idea how to fix this?


Solution

  • How exactly are you retrieving params in your api?

    If from the request body (i.e. not form the query string) then you should also pass the encoding argument to your Alamofire's request function as well with JSONEncoding.default value because by default the encoding is URLEncoding.default which means that parameters will be passed as query string.

    So change this:

    Alamofire.request("my-url", method: .post, parameters: parameters, headers: headers).responseJSON { (response) in
        debugPrint(response.result)
    }
    

    To:

    Alamofire.request("my-url", method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
        debugPrint(response.result)
    }
    

    From Alamofire's doc

    /// Creates a `DataRequest` using the default `SessionManager` to retrieve the contents of the specified `url`,
    /// `method`, `parameters`, `encoding` and `headers`.
    ///
    /// - parameter url:        The URL.
    /// - parameter method:     The HTTP method. `.get` by default.
    /// - parameter parameters: The parameters. `nil` by default.
    /// - parameter encoding:   The parameter encoding. `URLEncoding.default` by default.
    /// - parameter headers:    The HTTP headers. `nil` by default.
    ///
    /// - returns: The created `DataRequest`.
    @discardableResult
    public func request(
        _ url: URLConvertible,
        method: HTTPMethod = .get,
        parameters: Parameters? = nil,
        encoding: ParameterEncoding = URLEncoding.default,
        headers: HTTPHeaders? = nil)
        -> DataRequest
    {
        return SessionManager.default.request(
            url,
            method: method,
            parameters: parameters,
            encoding: encoding,
            headers: headers
        )
    }