2016-12-04 19 views
0

這裏是代碼。這是在我的UICollectionViewDataSource類中。collectionview只下載cellForItemAtIndexPath中的一個圖像

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

我落得這樣做:

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 
} 

另一個可能的解決方案是.resume問題?你可能想嘗試加入.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 
} 

我第三次和最後的解決方案是簡單擺脫if (photo.image == nil) {

希望這有助於

+0

嘿,謝謝你的詳細解答。我現在意識到,實際上只有一個圖像被下載,其餘的只是被下載,但'responseData'回調從不被調用。有任何想法嗎? –

相關問題