简体   繁体   中英

Swift UItableview with AlamofireImage crash when scrolling fast

Im using AlamofireImage to load images in an async way. It works quite well except when I scroll very fast the app crashes.

I assume it is because when maybe more than 10 requests are being sent in a very short period of time the app crashes (when I scroll fast). I also see a sudden spike in memory usage.

When I scroll slowly and maybe 4 requests are sent in a short period it does not crash.

Does anyone have a hint on how to prevent this? How can I cancel requests of invisible cells where the user has been scrolled by?

Here is the code:

// 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
}

EDIT: Log error is a NullPointer

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

Code line:

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

I load here the params schoolIdString and imageNameString from a previous query.

Thx for the answers. It was corrupt data from the database which made the URL corrupt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM