Search code examples
jsonswiftrestfirebasealamofire

Weird behavior occurs when sending a dictionary object that contains arrays of dictionary objects with Alamofire in Swift?


Here, I'm calling my API (Firebase Cloud Function) with the following dictionary object in Swift:

let data: [String: Any] = [
    "array1": [1, 2, 3],
    "array2": [
        [
            "key1": "value1",
            "key2": "value2"
        ],
        [
            "key3": "value3",
            "key4": "value4"
        ]
    ]
]

So, "array1" is an array of integers and "array2" is an array of dictionary objects. My cloud function DOES NOT do anything other than sending back what is received:

exports.testFunction = functions.https.onRequest((req, res) => {
    return res.status(200).send(req.body)
})

To call this cloud function, I am using Alamofire module:

Alamofire.request(
    "<url>",
    method: .post,
    parameters: data,
    encoding: URLEncoding.httpBody,
    headers: [
        "Authorization": "...",
        "Accept": "application/json"
    ]
).responseJSON { (response) in
    print(response)
}

The "print" statement above prints:

enter image description here

It means that there's nothing wrong with "array1", but the cloud function somehow receives "array2" as an array of a single object, who has 4 key and value pairs:

"array2": [
    {
        "key1": "value1",
        "key2": "value2",
        "key3": "value3",
        "key4": "value4"
    }
]

Why does this happen and how do I solve this problem?


Solution

  • Apparently the problem is with encoding parameter, simply switch "URLEncoding.httpBody" to "JSONEncoding.default" and the problem is solved!