mvasco
mvasco

Reputation: 5101

Not decoding JSON response to populate collection View

I am trying to populate a collection view with data receive from a remote PHP file.

The remote PHP file response is as follows:

[{"id":12,"nombre":"AGM","icono":"vCtAi1agmlogo.png"},{"id":10,"nombre":"Acer","icono":"h4QnIZacerlogo.png"},{"id":9,"nombre":"Apple","icono":"byjwZDapplelogo.png"},{"id":55,"nombre":"Cubot","icono":"xWQnfbcubotlogo.png"},{"id":110,"nombre":"Huawei","icono":"GYacqrhuaweilogo.png"},{"id":121,"nombre":"Innjoo","icono":"yWP39Ninnjoologo.png"},{"id":151,"nombre":"Lenovo","icono":"UL54jTlenovologo.png"},{"id":158,"nombre":"Majestic","icono":"ayDxNAmajesticlogo.png"},{"id":204,"nombre":"Polar","icono":"SQ3LXHpolarlogo.png"},{"id":218,"nombre":"Samsung","icono":"Vrs4hpSamsunglogo.jpg"},{"id":229,"nombre":"Sony","icono":"ZyFcI2sonylogo.png"},{"id":275,"nombre":"Xiaomi","icono":"5kRBCoxiaomilogo.png"}]

Here you have all methods for the collection View:

 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return marcas.count

    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

        print("MARCA:"+marcas[indexPath.row].nombre)
    }


    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "marca",for: indexPath) as! MarcasCollectionViewCell

        let foto_marca = marcas[indexPath.row].icono
        print(foto_marca)


        let url = URL(string: "https://../iconos/"+foto_marca)

        UIImage.loadFrom(url: url!) { image in
            cell.icono_marca.image = image

        }


        return cell


    }

And this is my download function to get the data:

   func downloadJSON(completed: @escaping () -> ()) {
        let url = URL(string: "https://.../Api.php")


        URLSession.shared.dataTask(with: url!) { (data,response,error) in

        print("Data:",data as Any)
        print("Response:",response as Any)
        print("Error:",error as Any)

        if error == nil {
            do {
                self.marcas = try JSONDecoder().decode([Marcas].self, from: data!)

                DispatchQueue.main.async {
                    completed()
                }

            }catch{
                print("JSON Error")
            }

        }
        }.resume()


    }

This is the model for Marcas:

struct Marcas:Decodable {

    let id: String
    let nombre: String
    let icono: String

}

As you may see, I have included three print tags to get the response from the server.

Here you have the print outputs for each tag:

Data: Optional(702 bytes)

Response: Optional(<NSHTTPURLResponse: 0x600000874be0> { URL: https://jogua.es/android_api/Api.php } { Status Code: 200, Headers {
    "Content-Encoding" =     (
        br
    );
    "Content-Type" =     (
        "text/html; charset=UTF-8"
    );
    Date =     (
        "Fri, 20 Mar 2020 17:38:10 GMT"
    );
    Server =     (
        cloudflare
    );
    Vary =     (
        "Accept-Encoding"
    );
    "cf-cache-status" =     (
        DYNAMIC
    );
    "cf-ray" =     (
        "5771348e09c868f4-CDG"
    );
    "expect-ct" =     (
        "max-age=604800, report-uri=\"https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct\""
    );
} })



Error: nil

At last, I a getting the JSON Error output.

What should I do to get the items for the collection View?

Upvotes: 0

Views: 32

Answers (1)

Rob
Rob

Reputation: 2164

Change the model to:

struct Marcas:Decodable {

let id: Int
let nombre, icono: String

}

Upvotes: 1

Related Questions