2017-03-04 41 views
-2

我試圖通過一個網址將照片上傳到我的tableView。我在「/////」註釋之間的代碼讓我的界面變得遲鈍而緩慢,我不明白爲什麼或者如何修復它。NSURL photo Swift

我做了一些研究,但是,這並不似乎工作(仍然滯後)

let userProfileChatImage = generalRoomDataArr[indexPath.row].photoURL 

    if let url = NSURL(string: userProfileChatImage!) { 

    if let data = NSData(contentsOf: url as URL) { 

     DispatchQueue.main.async(execute: {() -> Void in 
      imageView.image = UIImage(data: data as Data) 
     }) 


     } 
    } 

但是我不知道到底這是否是原因還是如何實現它,或者爲什麼。

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 

     let cell = tableView.dequeueReusableCell(withIdentifier: "cell") 



     let usernameLabel = cell?.viewWithTag(1) as! UILabel 
     usernameLabel.text = generalRoomDataArr[indexPath.row].username 

     let messageLabel = cell?.viewWithTag(2) as! UILabel 
     messageLabel.numberOfLines=0 // line wrap 
     messageLabel.lineBreakMode = NSLineBreakMode.byWordWrapping 
     messageLabel.text = generalRoomDataArr[indexPath.row].message 



     //initialize UI Profile Image 
     let imageView = cell?.viewWithTag(3) as! UIImageView 

     //Make Porfile Image Cirlce 
     imageView.layer.cornerRadius = imageView.frame.size.width/2 
     imageView.clipsToBounds = true 

     ///////////////////////////////////////////// 

     let userProfileChatImage = generalRoomDataArr[indexPath.row].photoURL 

     if let url = NSURL(string: userProfileChatImage!) { 

     if let data = NSData(contentsOf: url as URL) { 

     imageView.image = UIImage(data: data as Data) 


     ///////////////////////////////////////////// 






     // your cell coding 
     return cell! 
    } 

回答

0

您需要下載異步圖像。爲此,您可以使用以下不同庫:AlamofireImageSDWebImage

如果您不想使用某些庫,可以創建UIImageView的擴展,有關更多信息,請訪問此answer

0

NSData(contentsOf:)UIImage(contentsOf:)這樣的功能是同步的。他們立即執行網絡請求,在整個網絡作業完成之前不要繼續下一行。這凍結了當前線程。

正如你發現的那樣,在主線程中使用類似這樣的函數是一個壞主意。

蘋果建議您改用NSURLSessionURLSession在Swift 3中)。該類在後臺工作,然後在下載完成後調用委託方法或完成處理程序(這兩個選項都可用)。默認情況下,委託方法/完成處理程序在後臺線程上調用,因此您需要將UI調用封裝在將消息發送到主線程的代碼中。

我在Github上有一個名爲Async_demo的示例項目,它顯示了使用URLSession異步執行下載的一個非常簡單的示例。它故意不緩存結果,以便您可以反覆嘗試。在真實應用程序中,您希望將下載的圖像保存到磁盤上的文件中,並在發出新下載之前檢查它們是否已下載。您可以使用URL的散列來命名文件,以便在用戶嘗試再次顯示該單元格時從文件加載該文件。

正如Diego在他的回答中所說的那樣,還有各種您可以使用的第三方庫。