快速滚动时带有 AlamofireImage 的 Swift UItableview 崩溃

Posted

技术标签:

【中文标题】快速滚动时带有 AlamofireImage 的 Swift UItableview 崩溃【英文标题】:Swift UItableview with AlamofireImage crash when scrolling fast 【发布时间】:2016-07-21 07:29:15 【问题描述】:

我正在使用 AlamofireImage 以异步方式加载图像。 它工作得很好,除非我滚动得很快,应用程序崩溃。

我认为这是因为在很短的时间内发送了超过 10 个请求时,应用程序崩溃(当我快速滚动时)。 我还看到内存使用量突然激增。

当我缓慢滚动并且可能在短时间内发送 4 个请求时,它不会崩溃。

有没有人提示如何防止这种情况?如何取消用户滚动过的不可见单元格的请求?

代码如下:

// Dequeue your cell and other code goes here.
// with as! the cell is set to the custom cell class: DemoCell
// afterwards all data can be loaded from the JSON response into the cells
 override func tableView(tableView: UITableView, cellForRowAtIndexPath
    indexPath: NSIndexPath) -> UITableViewCell 

    let cell =
        tableView.dequeueReusableCellWithIdentifier("FoldingCell",
                                                    forIndexPath: indexPath) as! DemoCell
    cell.delegate = self

    //tag the cell with the indexpath row number to make sure the loaded asynch image corresponds to the right cell
    cell.tag = indexPath.row
//clear cell of eventually reused images
    cell.schoolCoverImage.image = UIImage()
    cell.schoolBiggerImage.image = UIImage()

//TODO: set all custom cell properties here (retrieve JSON and set in cell), use indexPath.row as arraypointer

    let resultList = self.items["result"] as! [[String: AnyObject]]
    let itemForThisRow = resultList[indexPath.row]

    cell.schoolNameClosedCell.text = itemForThisRow["name"] as! String
    cell.schoolNameOpenedCell.text = itemForThisRow["name"] as! String

    self.schoolIdHelperField = itemForThisRow["name"] as! String

    cell.schoolIntroText.text = itemForThisRow["name"] as! String

// set the button's tag like below.
    cell.innerCellButton.tag = indexPath.row

//call method when button inside cell is tapped
    cell.innerCellButton.addTarget(self, action: #selector(MainTableViewController.cellButtonTapped(_:)), forControlEvents: .TouchUpInside)


      cell.schoolIntroText.text = "We from xx University..."

 //handle the image from a separate API call
    let schoolIdNumber = itemForThisRow["sco_id"] as! NSInteger
    let schoolIdString = String(schoolIdNumber)
 //TOCHeck: maybe Id is not correct and should be replaced by indexCount


    let imageNameString = itemForThisRow["image"] as! String


//only load the image of the cell which is visible in the screen 
 //     print("current cells visible?")
//    print(tableView.visibleCells)
 //   print("currentCell")
 //   print(cell.tag)
//   if(tableView.visibleCells.contains(cell)) 

    let urlRequest = NSURLRequest(URL: NSURL(string: "https://ol-web-  test.herokuapp.com/olweb/api/v1/schools/"+schoolIdString+"/image/"+imageNameString)!)

     print(urlRequest)

    //does cell number/tag match current indexpath row?
    if(cell.tag == indexPath.row) 

   //use cache in case image has been saved to cache already, otherwise get image from networking

     if(self.photoCache.imageForRequest(urlRequest) != nil) 

        cell.schoolCoverImage.image = photoCache.imageForRequest(urlRequest)
        cell.schoolBiggerImage.image = photoCache.imageForRequest(urlRequest)
        print("image from cache loaded")
     
     else
     

        self.imageDownloader.downloadImage(URLRequest: urlRequest)  response in
            print(response.request)
            print(response.response)
            debugPrint(response.result)

            if let image = response.result.value 
                print("here comes the printed image:: ")
                print(image)
                print(schoolIdString)

                //set image to the cell

                    cell.schoolCoverImage.image = image
                    cell.schoolBiggerImage.image = image

                    self.photoCache.addImage(image, forRequest: urlRequest)
                    print("image from network loaded and added to cache")
                    print(self.photoCache.memoryCapacity.description)
                   print(self.photoCache.memoryUsage.description)

            
    
        
 

    return cell

编辑:日志错误是 NullPointer

 30/image/Beet_Language_Bournemouth_1.jpeg 
fatal error: unexpectedly found nil while unwrapping an Optional va lue

代码行:

let urlRequest = NSURLRequest(URL: NSURL(string: "https://ol-web-  test.herokuapp.com/olweb/api/v1/schools/"+schoolIdString+"/image/"+imageNameString)!)

我在此处加载来自先前查询的参数 schoolIdString 和 imageNameString。

【问题讨论】:

查看MJ-TableView-Image-Swift 如果您可以粘贴崩溃中的错误日志会很好。 它应该来自您的图片下载器。尝试使用仪器检查raywenderlich.com/97886/… 添加了错误日志。它是一个空指针。但奇怪的是,只有当我快速滚动并在很短的时间内有 10 多个请求时才会发生这种情况 【参考方案1】:

谢谢你的答案。是数据库中的数据损坏导致 URL 损坏

【讨论】:

以上是关于快速滚动时带有 AlamofireImage 的 Swift UItableview 崩溃的主要内容,如果未能解决你的问题,请参考以下文章

AlamofireImage 占位符图像在缓存图像之前简要显示 v3.1

Swift - AlamofireImage 下载多个 URL 并显示在 CollectionView 中

AlamofireImage 缓存在我的应用程序中不起作用

当 url 不是图像时,使用 AlamoFireImage 未捕获的 NSException 类型异常

如何在快速向上和向下滚动表格时停止自动重新加载表格视图? [关闭]

使用表格视图快速搜索控制器滚动