I have an API where I PUT
stuff to. I need to make sure to wait until I get an http 200 response from the server, but I don’t know how to await that using Alamofire because my response itself if empty. So it’s just an http 200 with no content.
I only can find async functions that e.g. serialize a String
or Data
or a Decodable
, but they don’t work if my response is empty.
Is there a way to await something like that in Alamofire?
3
Answers
If Alamofire does not provide a method for your purpose, then you will have wrap the old Alamofire methods that uses closures as below:
I know that your question is about async/await from Alamofire, but is good to know that the http status codes 204 and 205 are exactly for this. Which means that if you have access to the server code you could send the empty responses with the http status code 204 and 205 instead of 200 and then Alamofire would not generate any errors. But assuming you don’t have access to the server code and you need to parse an empty response as correct then you could use the following code:
And for a real and complete example of how async/await from Alamofire or any other async context look this code:
Alamofire already supports this, you just need to choose a form. Your biggest issue will be accepting a 200 with no data, as that’s technically invalid since only 204 or 205 are supposed to be empty.
All Alamofire responses require some sort of payload type, but Alamofire provides an
Empty
type to fill this role forDecodable
. So the simplest way is to use theNote, if you already have an
Empty
type or are importing Combine in the same file as this code, you may need to disambiguate by usingAlamofire.Empty
.