从网络显示图像时表视图滞后

时间:2016-12-10 07:11:46

标签: ios swift uitableview

我正在创建一个小应用程序,用于在Flickr中显示TableView中的图像。该应用程序工作正常但我在滚动表视图时遇到问题,我的tableview滞后很多。我认为问题可能出在GCD或Threads上,我是网络和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 个答案:

答案 0 :(得分: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
}