I'm dealing a JSON service that returns 200 as the response code and "null" as the response body to indicate when the requested item couldn't be found.
I've read up on the usage of emptyResponseCodes: [200, ...]
, but it doesn't seem to address this particular scenario. What would be the recommended way for dealing with this if I still want to use responseDecodable()
?
I've tried the following, but the failure case occurs:
self.sessionManager.request(self.url, headers: self.headers).validate().responseDecodable(of: T.self, queue: self.queue, emptyResponseCodes: [200, 204]) { response in
switch response.result {
case .success(let data):
completion(data)
case .failure(let error):
onFailure(error)
}
}.resume()
Would a custom response serializer be the best approach? Something like this?
self.sessionManager.request(self.url, headers: self.headers).response(responseSerializer: NullResponseSerializer<T>()) { response in
...
Where NullResponseSerializer would be something like:
struct NullResponseSerializer<T: Decodable>: ResponseSerializer {
func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Result<T, Error> {
guard let response = response else { return .failure(error!) }
do {
if response.statusCode >= 200 || response.statusCode <= 300 {
let nullData = Data(bytes: [0x6E, 0x75, 0x6C, 0x6C] as [UInt8], count: 4)
if let d = data, d == nullData {
print("need to deal with null data...")
// TODO: Deal with this case.
} else {
let result = try serialize(request: request, response: response, data: data, error: nil)
return .success(result as! T)
}
} else {
return .failure(error)
}
} catch {
return .failure(error)
}
}
}
Thanks!