2

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()
}
MoeinDeveloper
  • 251
  • 1
  • 2
  • 11

1 Answers1

1

In your codable struct, you should implement custom init and set your data as a optional


init(from decoder: Decoder) throws {
     let values = try decoder.container(keyedBy: CodingKeys.self)
     YourField = try? values.decode(TypeOFField.self, forKey: .yourfiled)
}
Mac3n
  • 4,189
  • 3
  • 16
  • 29