Trying out the request on Postman, the "data" of the response is an empty dictionary.
However, when I try that in swift using Alamofire, "data" gets misinterpreted as an empty array. What could I be doing wrong?
Raw response using debugPrint(response)
prints the following:
[Response]:
[Status Code]: 200
[Headers]:
Access-Control-Allow-Origin: *
Alt-Svc: h3=":443"; ma=2592000, h3-29=":443"; ma=2592000, h3-Q050=":443"; ma=2592000, h3-Q046=":443"; ma=2592000, h3-Q043=":443"; ma=2592000, quic=":443"; ma=2592000; v="43,46"
Cache-Control: no-cache, private
Content-Encoding: br
Content-Length: 71
Content-Type: application/json
Date: Tue, 31 Jan 2023 16:32:18 GMT
Vary: Accept-Encoding
x-powered-by: PHP/8.0.24
x-ratelimit-limit: 60
x-ratelimit-remaining: 59
[Body]:
{"status":false,"message":"Kullanu0131cu0131 bilgileri hatalu0131.","data":[]}
Tried changing the encoding and headers of the request, none was helpful.
2
Answers
This isn’t an Alamofire issue, it’s an error from
JSONDecoder
. You can check your actual response by printing the raw response in Alamofire (which you don’t post any code for).That will print a
String
version of the response body (unless it’s very large) which you can use to see what you’re actually receiving.You can also check your actual response using a proxy like Proxyman or a traffic inspector like Wireshark and see what you’re actually getting. It seems likely you’re actually receiving an array.
I’ve come across this odd way of representing
null
from a server (openweathermap), where instead ofnull
, it uses{}
.To work with this, I used a custom decoder, something like:
with declaration,
let data: [String]?
or whatever the array holds.Note this is a
JSONDecoder
behaviour, not Alamofire, I was usingURLSession.shared...
with this. When theJSONDecoder
tries to decode this{}
, it crashes, because it is not an anull
and it not an array either. Postman is probably more forgiving than SwiftJSONDecoder
. Alamofire tries to decodedata
as an array, because you probably declared it as an array in your struct/class to decode.EDIT-1:
here is the SwiftUI code I used to test my answer (same approach for UIKit and Alamofire):