func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! UsersCollectionViewCell
someRequest(username: self.usernameUrl) { (userInfo, error) in
guard let userInfo = userInfo else {
// present error
return
}
print("Running")
let user_image_url = userInfo.items.map{($0.avatarURL)}
cell.userCellLabel.text = user_name[indexPath.item]
}
return cell
}
为什么当我在viewDidAppear上调用reloadData时,someRequest(...)中的代码未运行?
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.collectionViewUsers.reloadData()
}
P.s。 Somerequest只需执行Alamofire获取
异步Alamofire请求必须在cellForItemAt
处理程序之外。 viewDidLoad
是开始获取的好地方,异步调用完成后,别忘了重新加载collectionview。
var user_image_url: String?
override func viewDidLoad(_ animated: Bool) {
someRequest(username: self.usernameUrl) { (userInfo, error) in
guard let userInfo = userInfo else {
// present error
return
}
print("Running")
user_image_url = userInfo.items.map{($0.avatarURL)}
self.collectionViewUsers.reloadData()
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! UsersCollectionViewCell
if let user_image_url = user_image_url {
//user_image_url is avaliable
}
return cell
}