2016-12-04 2 views
0

ここにコードがあります。これは私のUICollectionViewDataSourceクラスにあります。 collectionviewはcellForItemAtIndexPath内の1つのイメージのみをダウンロードします

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 
} 

progress.fractionCompleted

は、画像がダウンロードされていることを示しているが、私は、画像のどれも更新されていない理由はわかりません。それはAlamofireが非同期に動作するためですか?アドバイスをいただければ幸いです。

答えて

0

を助けif (photo.image == nil) {

希望を取り除くことです。

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 
1

ここには3つの解決策があります。最初のものは、バックグラウンドスレッドの問題のためです。 collectionView.reloadDataの代わりに、次を使用してください。

DispatchQueue.main.async { 
collectionView.reloadData 
} 

もう1つの可能な解決策は、再開問題ですか?あなたは以下の私の例のように.resumeを追加しようとする場合があります:

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() 
      } 
     }.resume 
    } else { 
     cell.updateWithImage(image: photo.image) 
    } 
    return cell 
} 

私の3番目と最終的な解決策は単純で、これは私がこれをやってしまった

+0

ちょっと、徹底的な答えをありがとう。残りの部分はダウンロードされたようですが、 'responseData'コールバックは決して呼び出されません。何か案は? –

関連する問題