1

I'm trying to connect to a 3rd party API that requires an auth token as a query parameter to a POST request with JSON body using Alamofire 4.

A similar question was asked here: Multiple encoding types for Alamofire Request

I'm trying to implement the accepted answer using Alamofire 4 (answer used Alamofire 3).

Here's what I'm doing:

let url = URL(string: urlString)!
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"

let bodyParameters: [String: AnyObject] = [
    "inviter": inviterId as AnyObject,
    "invitee": inviteeId as AnyObject
]

let requestWithBody = try Alamofire.JSONEncoding.default.encode(urlRequest, with: bodyParameters)

let queryParameters: [String: AnyObject] = [
    "api_token": tokenString as AnyObject
]

var compositeRequest = try Alamofire.URLEncoding.default.encode(urlRequest, with: queryParameters)
compositeRequest.httpBody = requestWithBody.httpBody
return compositeRequest

The code compiles and executes fine. However, when I execute the request, and print the response.request to the console, the request URL doesn't include the query parameter.

Dragonspell
  • 327
  • 4
  • 13

1 Answers1

1

This version of the original seems to be working OK for me (AF4/Swift4):

fileprivate func multiEncodedURLRequest(
    method: HTTPMethod,
    requestURL: URL,
    parameters: Parameters,
    bodyParameters: Parameters) -> URLRequest
{
    let request = URLRequest(url: requestURL)

    do {
        var urlRequest = try URLEncoding.default.encode(request, with: parameters)
        var bodyRequest = try JSONEncoding.default.encode(request, with: bodyParameters)

        urlRequest.httpMethod = method.rawValue
        urlRequest.httpBody = bodyRequest.httpBody

        return urlRequest
    }
    catch {
        return request
    }
}