I have written a function with generic type result.
private func fetch<Request, Response>(_ endpoint: Types.EndPoint,
method: HTTPMethod = .get,
body: Request? = nil,
then callback: ((Result<Response, Types.Error>) -> Void)? = nil
) where Request: Encodable, Response: Decodable {
//Network request creation...
let dataTask = URLSession.shared
.dataTask(with: urlRequest) { data, response, error in
if let error = error {
print("Fetch error: \(error)")
callback?(.failure(.generic(reason: "Could not fetch data :\(error.localizedDescription)")))
} else {
if let data = data {
do {
let result = try self.decoder.decode(Response.self, from: data) // **exception here**
callback?(.success(result))
} catch {
print("Decoding error: \(error)")
callback?(.failure(.generic(reason: "Could not decode data :\(error.localizedDescription)")))
}
}
}
}
}
......
apiClient.fetch(.updateUser, API.Types.Request.User) { (result: Result<API.Types.Response.Empty, API.Types.Error>) in
//handle result
}
API.Types.Response.Empty is a struct,
struct Empty: Decodable {}
Now my question is, when above api is called, server returns an empty response (Content-Length
is 0
) when it is successful. (status-code
is 200
). only few apis do this, other apis return some kind of json with the response.
When response data is empty, json decoding throws an exception
Unable to parse empty data." UserInfo={NSDebugDescription=Unable to parse empty data
How do I properly handle this situation? Any help would be much appreciated.