lpy
lpy

Reputation: 25

Cannot get array to display in the collection view (Swift 4)

I tested the collection view can displayed the content. However, I can't retrieve and add array result in the collection view.

Here is my code:

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

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

    cell.FoodTitle.text = arr[indexPath.row].title
    cell.Food.image = arr[indexPath.row].image_url

    return cell
}

About the array, it is a function inside the fetchFoodList.

func fetchFoodList(){
let url = URL(string: "MYAPI.json")
    guard let unwrappedUrl = url else { return }
    let task = URLSession.shared.dataTask(with: unwrappedUrl, completionHandler: {(data, response, error)in
        if error != nil{
            print(error!)
        } else {
            if let urlContent = data{
                do {
                    let json = try JSON(data:data!)
                    let recipes = json["recipes"]

                    for arr in recipes.arrayValue{
                        print(arr["title"])

                        print(arr["image_url"])
                    }
                }
                catch{
                    print("JSON Processing Failed")
                }
            }
        }
    })
    task.resume()

    }
 }

However, the array result title and image_url can displayed in the console.

Upvotes: 0

Views: 111

Answers (1)

Gowri G
Gowri G

Reputation: 420

After appending the array list need to reload collection like this

collectionView.reloadData()

Upvotes: 1

Related Questions