0

When I print dictionary["name"] it showed up as what I wanted, but if I append it to my class it appeared as nil, this also happened when I append dictionary["name"] as? String to an array here is my code:

class HomeController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

        var test: [Test]?

        @IBOutlet weak var cView: UICollectionView!

        func fetchJSON () {
            let url = URL(string: "My JSON File")
            URLSession.shared.dataTask(with: url!) { (data, response, error) in
                if error != nil {
                    print("ERROR")
                    return
                }
                do {
                    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
                    self.test = [Test]()
                    for dictionary in json as! [[String: AnyObject]] {
                        let tes = Test()
                        tes.name = dictionary["name"] as? String
                        tes.country = dictionary["country"] as? String
                        self.test?.append(tes)
                    }

                }
                catch {
                    print("ERROR")
                }
            }.resume()
        }


        override func viewDidLoad() {
            super.viewDidLoad()
            fetchJSON()
        }
        override func viewDidAppear(_ animated: Bool) {
            cView.reloadData()
        }

        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return test?.count ?? 0
        }
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 1
        }
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! Cell
            cell.nameLabel.text = test?[indexPath.item].name
            cell.countryLabel.text = test?[indexPath.item].country
            return cell

        }
    }
Hamish
  • 78,605
  • 19
  • 187
  • 280
Riven
  • 536
  • 1
  • 5
  • 17
  • This call is asynchronous. You have to use a callback (completion handler) to get back the values. Example linked, but there's many other ones on the site. – Eric Aya Mar 14 '17 at 11:47
  • Just call `cView.reloadData()` after populating `test` in the completion closure, rather than in `viewDidAppear`. – Hamish Mar 14 '17 at 11:51
  • @EricAya thanks i'll look into it – Riven Mar 14 '17 at 11:57
  • @Hamish the problem lies when i put the dictionary into another variable – Riven Mar 14 '17 at 11:57

0 Answers0