0

I have a collection view with API data but, although I reloaddata() in dispatchQueue.main.async, I am getting Thread 1: EXC_BAD_INSTRUCTION on collectionview numberOfItemsInSection().

var games : Game?

override func viewDidLoad() {
    super.viewDidLoad()

    gamesCollectionView.register(GameCollectionViewCell.self, forCellWithReuseIdentifier: GameCollectionViewCell.identifier)
    gamesCollectionView.delegate = self
    gamesCollectionView.dataSource = self
    gamesCollectionView.allowsMultipleSelection = false
    
    fetchData()
    
    DispatchQueue.main.async {
        self.gamesCollectionView.reloadData()
    }
}

func fetchData(){
        AF.request("https://api.rawg.io/api/games", method: .get, parameters: nil, headers: nil, interceptor: nil).validate(statusCode: 200 ..< 299).responseJSON { AFdata in
   do {
       let game = try
       JSONDecoder().decode(Game.self, from: AFdata.data!)
       self.games = game
      }
    catch let jsonErr {
      print(jsonErr)
    }
   }
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    
    return (games?.results!.count)!
}
AtakanK
  • 1
  • 1

1 Answers1

1
do{
     let game = try JSONDecoder().decode(Game.self, from: AFdata.data!)
     self.games = game    
     DispatchQueue.main.async {
         self.gamesCollectionView.reloadData()//Reload here
     } 
}catch let jsonErr{
     print(jsonErr)
}

one more thing i check your api response it will gives me

{ "error": "The key parameter is not provided" }

check that response in your code and let me know.

jatin fl
  • 157
  • 6