I got an image url array inside a post object array I want to display this post array in a table view and display the images as a collection view inside the table view. How can I enter image description heredo it? I tired to use a int i as an indicator but it doesn't work.
here are the codes
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCell", for: indexPath) as! HomeTableViewCell
cell.postsText.text = postLists[indexPath.row].postText
i = indexPath.row
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return (postLists[i].imageUrlList?.count)!
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as! PhotosCollectionCell
let url = postLists[i].imageUrlList![indexPath.row]
let imgUrl = URL(string: url)
URLSession.shared.dataTask(with: imgUrl!, completionHandler: { (data, response, error) in
if error != nil {
// if download hits an error, so lets return out
print(error)
return
}
// if there is no error happens...
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // in half a second...
cell.postPhoto.image = UIImage(data: data!)
}
}).resume()
return cell
}
Never forcefully wrap optional ever Until you are very sure. (I can comment also but I want to add more details which is not suitable for comment so forgive )
Another thing I can see is use indexPath.item
in collectionView
not indexPath.row
both will be same but this is standard I always follows.
You are not calling URLSession.data
task in background thread. it is always recommend to do so. my suggestion is to that you should use some third party library like SDWebIamge which will helpful to you cache already downloaded image.
Wy Crash:
What I am seeing is Crash because of your variable i
in your code postLists[i].
What you should do
Inside
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
you can set tag to your collection view like
cell.yourCollectionViewObject.tag = indexPath.row
and replace
let url = postLists[i].imageUrlList![indexPath.row]
with
let url = postLists[collectionView.tag].imageUrlList![indexPath.row]
Hope it is helpful