2017-10-17 50 views
-1

我有一個字符串,我用逗號分隔的圖像鏈接。下面是我如何將它分解成一個數組:let imagesLinks = imageLins.components(separatedBy: ",")。然後我用for循環得到一個鏈接,下載的圖片,並將其在UIImage陣列以這種方式儲存:SDWebImage給零無網址

for imag in imagesLinks 
     { 
      let img = UIImageView() 

      print("\(baseReportImageURL)\(imag)") 

      img.sd_setImage(with: URL(string: "\(baseReportImageURL)\(imag)"), placeholderImage: nil) 
      imagesArray.append(img.image!) 
     } 

print語句是給我的,當我在瀏覽器中打開正確的URL下載圖片。問題出在我追加陣列的行上,即imagesArray.append(img.image!)。我得到:

fatal error: unexpectedly found nil while unwrapping an Optional value

fatal error: unexpectedly found nil while unwrapping an Optional value

那麼,什麼將是這個正確的解決方案?

UPDATE

我的問題是不同的,因爲我使用SDWebImage,當我使用完畢塊有應用程序的一個奇怪的行爲:

img.sd_setImage(with: imgURL, placeholderImage: nil,options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in 
       activityIndicator.stopAnimating() 
       imagesArray.append(image!) 
       self.photoCollection.reloadData() 
      }) 

所以不斷旋轉的活動指示燈,當我返回並再次推送視圖時,它立即加載圖像。所以我認爲在下載圖像時不會調用完成塊,但爲什麼?

+1

的可能的複製[檢查URL圖像存在(https://stackoverflow.com/questions/29962938/check-if -url-image-exist) – Desdenova

+0

確保你的'imageLinks'沒有空鏈接。 –

+0

@Chaudhry Talha更新後獲取圖像數組? –

回答

0

這是因爲

imagesArray.append(img.image!) 

圖片需要一段時間進行下載。當你在那時做imagesArray.append(img.image!)有可能你的圖像沒有設置到你的圖像視圖,這意味着你正試圖在你的imageArray中添加nil

第二件事你爲什麼要將圖像存儲在數組中?您有urls陣列,並且您每次使用SDWebImage時都要使用SDWebImage顯示圖像。無需存儲陣列!

如果你想要數組中的圖像而不是使用NSUrlSession異步請求與完成處理程序和完成處理程序添加圖像到您的數組!

+0

我有一個逗號分隔的字符串與圖像的URL和SDWebImage完成塊不以我的方式工作。請看看您是否可以添加我在問題更新部分添加的內容。 –

0

將圖像追加到sd_setImage完成塊中的圖像數組中。 當您嘗試將其添加到數組中時,圖像尚未下載,並在添加之前檢查圖像是否不相等。

0

此塊圖像下載下載後執行操作(添加圖片)

cell.appIcon.sd_setImage(with: url!, placeholderImage: UIImage(named: "App-Default"),options: SDWebImageOptions(rawValue: 0), completed: { (image, error, cacheType, imageURL) in 
// Perform operation. 
//append Image Here 
}) 
+0

有一個奇怪的行爲。請看我最新的問題。 –