3

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()
}

1 Answer 1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.