Search code examples
swiftuicollectionviewalamofire

collectionview only downloading one image in cellForItemAtIndexPath


Here is the code. This is in my UICollectionViewDataSource class.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let identifier = "UICollectionViewCell"
    let photo = photos[indexPath.row]
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! PhotoCollectionViewCell
    let url = ImageUploaderAPI.urlForPhotoPath(photoTitle: photo.remoteURL)

    if (photo.image == nil) {
        Alamofire.download(url).downloadProgress { progress in
                print("Download Progress: \(progress.fractionCompleted)")
            }
            .responseData { response in
            if let data = response.result.value {
                let image = UIImage(data: data)
                photo.image = image!
                cell.updateWithImage(image: image)
                print("Downloaded: " + url.absoluteString)
                collectionView.reloadData()
            }
        }
    } else {
        cell.updateWithImage(image: photo.image)
    }
    return cell
}

The progress.fractionCompleted is showing that the images are being downloaded, but I'm not sure why none of the images are updating. Is it because of how Alamofire works asynchronously? Any advice would be appreciated.


Solution

  • I ended up doing this:

    cell.activityIndicator.startAnimating()
        if (photo.image == nil) {
            let dataTask = URLSession.shared.dataTask(with: url) {
                data, response, error in
                    if error == nil {
                        if let data = data {
                            let image = UIImage(data: data)
    
                            print("Downloaded: " + url.absoluteString)
    
                            DispatchQueue.main.async {
                                photo.image = image!
                                collectionView.reloadItems(at: [indexPath])
    
                            }
                        }
                    } else {
                        print(error)
                    }
            }
            dataTask.resume()
        } else {
            cell.updateWithImage(image: photo.image)
        }
        cell.activityIndicator.stopAnimating()
        cell.activityIndicator.isHidden = true
    
        return cell