2016-07-21 2 views
0

Im, использующий AlamofireImage для загрузки изображений асинхронным способом. Он работает довольно хорошо, за исключением случаев, когда я прокручиваю очень быстро, приложение падает.Swift UItableview с крахом 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 
} 

EDIT: бревенчатый ошибка является 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)!) 

загружаю здесь Params schoolIdString и imageNameString от предыдущий запрос.

+0

проверьте это [MJ-TableView-Image-Swift] (https://github.com/JaleelNazir/MJ-TableView-Image-Swift) –

+0

было бы хорошо, если вы можете вставить журнал ошибок из аварии. –

+0

это должно быть из вашего загрузчика изображений. попробуйте использовать инструменты для проверки https://www.raywenderlich.com/97886/instruments-tutorial-with-swift-getting-started – xmhafiz

ответ

0

Thx для ответов. Это были поврежденные данные из базы данных, которые сделали URL-адрес поврежденным

Смежные вопросы