Swift CollectionView在API调用后重新加载数据
我有一个包含API数据的集合视图,但是,尽管我在Swift CollectionView在API调用后重新加载数据,swift,Swift,我有一个包含API数据的集合视图,但是,尽管我在dispatchQueue.main.async中使用了reloaddata(),但我在collectionview numberOfItemsInSection()上得到了线程1:EXC\u BAD\u指令 var游戏:游戏? 重写func viewDidLoad(){ super.viewDidLoad() gamesCollectionView.register(GameCollectionViewCell.self,forCellWithR
dispatchQueue.main.async
中使用了reloaddata()
,但我在collectionview numberOfItemsInSection()上得到了线程1:EXC\u BAD\u指令
var游戏:游戏?
重写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,方法:.get,参数:nil,头:nil,拦截器:nil).validate(状态代码:200..<299).responseJSON{AFdata in
做{
让游戏=尝试
JSONDecoder().decode(Game.self,from:AFdata.data!)
self.games=游戏
}
接球手{
打印(JSONER)
}
}
}
func collectionView(collectionView:UICollectionView,numberOfItemsInSection:Int)->Int{
返回(游戏?.results!.count)!
}
还有一件事我会检查你的api响应,它会给我
{
“错误”:“未提供密钥参数”
}
检查代码中的响应并告诉我。因为API调用是异步的,所以在获得API响应后需要重新加载collectionView。这实际上是我要问的问题。你说得对。同时在主线程中添加gamesCollectionView reload()。@Kudos没问题。默认情况下,AF将其完成处理程序分派到主线程。它正在工作,但是,当我在UICollectionViewDataSource中分配games.results.count的节数时,我得到EXC_BAD_指令返回(games?.results!.count)!检查那部分,你得到结果了吗?
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)!
}
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)
}