I have an API that gives me two different responses.
here is when data is correct and I have objects:
{ "latlng": [My Objects] }
and here is when my data is empty:
[]
so my question is how to handle this empty response when I'm using jsonDecoder?
my networking function:
func performNetworkingTaskWithParams<T: Codable>(endpoint: EndPointType, type: T.Type, params: [String : String],completion: ((_ response: T)-> Void)?) {
let url = endpoint.baseURL.appendingPathComponent(endpoint.path)
let config = URLSessionConfiguration.default
config.httpAdditionalHeaders = [
"Accept" : "application/json",
"Content-Type" : "application/x-www-form-urlencoded"
]
var urlRequest = URLRequest(url: url)
let session = URLSession(configuration: config)
urlRequest.encodeParameters(parameters: params)
let taskSession = session.dataTask(with: urlRequest) { (data, response, error) in
if let myError = error {
print("request error:\(myError)")
return
}
guard let responseData = data else {
print("response is null!")
return
}
let response = Response(data: responseData)
guard let decoded = response.decode(type) else {
print("cannot decode data!")
return
}
completion?(decoded)
}
taskSession.resume()
}