2016-10-14 129 views
0

我的圖片有問題。我的表格視圖很慢。我如何通過異步調用來改進?在創建細胞的功能,我有這樣的:如何異步加載圖像以提高表視圖性能?

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    //IMPOSTA l'identifier della cella campione indexpath restituisce il numero della cella 
    let cella = tableView.dequeueReusableCellWithIdentifier("record_cat", forIndexPath: indexPath) as! myTableViewCell 
    if (musica.shared.id.count > 0) && (cella_select < musica.shared.id.count){ 
     //label personalizzata cella con inserimento dell ARRAY IN BASE ALL'INDICE (indexPath.row indica il numero della cella quindi associa cella ad array) 
     print(indexPath.row) 
     cella.button_favorite.tag = indexPath.row 
     cella.titolo.text = musica.shared.titles[indexPath.row] 
     cella.artista.text = musica.shared.artists[indexPath.row] 
     cella.logo_new.hidden = true 
     let url_img = NSURL(string: "https://tuunes.co/app/upload/\(musica.shared.images[indexPath.row])") 
     let data_img = NSData(contentsOfURL: url_img!) 
     if (data_img != nil){ 
      cella.immagine.image = UIImage(data: data_img!) 
     } 
     else{ 
      cella.immagine.image = UIImage(named: "cover-img-list") 
     } 
    } 
    else{ 
     return cella 
    } 
    return cella 
} 
+0

表是因爲'讓data_img = NSData的慢(contentsOfURL:url_img)'。使用'SDWebImage'或'KingFisher' –

+0

是否適合您? –

回答

0

只需通過安裝SDWebImageCocoaPods

如何使用它

導入SDWebImageViewController您的表是:

import SDWebImage 

然後將此代碼替換爲cellForRowAtIndexPath

let data_img = NSData(contentsOfURL: url_img!) 
if (data_img != nil){ 
     cella.immagine.image = UIImage(data: data_img!) 
} else { 
     cella.immagine.image = UIImage(named: "cover-img-list") 
} 

cella.immagine.sd_setImageWithURL(url_img!, placeholderImage: UIImage(named: "cover-img-list")) 
0
//Set placeholder sync 
cella.immagine.image = UIImage(named: "cover-img-list") 

if let urlImg = NSURL(string: "https://tuunes.co/app/upload/\(musica.shared.images[indexPath.row])") { 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { 
     //load data on the background thread 
     if let dataImg = NSData(contentsOfURL: urlImg) { 
      dispatch_async(dispatch_get_main_queue()) { 
       //Update UI on the main thread 
       cella.immagine.image = UIImage(data: dataImg) 
      } 
     } 
    } 
} 
+0

這不會緩存圖像 –