2016-12-10 69 views
0

我正在創建一個小應用程序,用於在Flickr的TableView中顯示圖像。該應用程序工作正常,但我滾動表視圖時遇到問題,我的tableview滯後很多。我認爲這個問題可能與GCD或線程有關,我是網絡和GCD的新手,這是我的代碼從Flickr API獲取圖像。從網絡顯示圖像時的表視圖滯後

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = flickrTableView.dequeueReusableCellWithIdentifier("cell") as! FlickerTableCell 
    let flickr = flickrArray[indexPath.row] 
    dispatch_async(dispatch_get_main_queue(), { 
    cell.imageViewFlickr.image = flickr.getFlickrImage() 
    }) 

    cell.labelFlickrTitle.text = flickr.title 
    return cell 
} 

//起作用以從Flickr獲得圖像

func getFlickrImage()->UIImage{ 
    let imageURL = NSURL(string: "https://farm\(farm).staticflickr.com/\(server)/\(photoId)_\(secret)_m.jpg")! 
    var flickrImage = UIImage() 
    if let imageData = NSData(contentsOfURL: imageURL) { 
      flickrImage = UIImage(data: imageData)! 

    } else { 

     print("Image does not exist at \(imageURL)") 
    } 
    return flickrImage 
} 

回答

1

你的方法來從網絡即getFlickrImage()取圖像是其響應,並作爲網絡呼叫是同步方法,這樣的表格單元等待在主線程中凍結或滯後UI。你可以用你的網絡電話在異步方法和使用完成處理程序來更新主線程,如UI:

func getFlickrImage(completion:UIImage ->()){ 
    let imageURL = NSURL(string: "https://farm\(farm).staticflickr.com/\(server)/\(photoId)_\(secret)_m.jpg")! 
    var flickrImage = UIImage() 

    let download = dispatch_queue_create("download", nil) 
    dispatch_async(download) { 

     if let imageData = NSData(contentsOfURL: imageURL) { 
      dispatch_async(dispatch_get_main_queue(), { 
       flickrImage = UIImage(data: imageData)! 
       completion(flickrImage) 
      }) 
     } else { 

      print("Image does not exist at \(imageURL)") 
      completion(flickrImage) 
     } 
    } 

} 

你的cellForRowAtIndexPath將是這樣的:

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
    let cell = flickrTableView.dequeueReusableCellWithIdentifier("cell") as! FlickerTableCell 
    let flickr = flickrArray[indexPath.row] 
    flickr.getFlickrImage { (photo) in 
     dispatch_async(dispatch_get_main_queue(), { 
      cell.imageViewFlickr.image = photo 
     }) 
    } 
    cell.labelFlickrTitle.text = flickr.title 
    return cell 
} 
+0

感謝@ abhijeet-mallick的快速反應,它真的爲我+1 –