Cristian
Cristian

Reputation: 67

tableView.reload() freezes the app while running

I have this huge problem! I'm fetching data from firebase, saving it to an array and then using cellForRowAt I populate the row. In the end I run tableView.reload(). I have to run tableView.reload() because cellForRowAt runs before the array can populate with db elements.

The problem is that when I run tableView.reload() the app freezes and if I click any button it won't work. The button runs only when tableView.reload() finished running.

I run tableView.reload() as soon as the array have been populated.

Some code:

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ImageTableViewCell
        
        let preview2 = imageDownload(images[counter!]["previewURL"]! as! String)
        cell.img2.imagePreview = preview2
        cell.img2.setImage(preview2, for: .normal)
        cell.img2.addTarget(self, action: #selector(imgTapped(_:)), for: .touchUpInside)
        
        let preview1 = imageDownload(images[counter!-1]["previewURL"]! as! String)
        cell.img1.imagePreview = preview1
        cell.img1.setImage(preview1, for: .normal)
        cell.img1.addTarget(self, action: #selector(imgTapped(_:)), for: .touchUpInside)
        counter = counter! - 2
        
        return cell
    }

func imageDownload(_ url: String) -> UIImage {
     let imageURL = URL(string: url)
     let imageData = try? Data(contentsOf: imageURL!)
     let image = UIImage(data: imageData!)
     return image!
}

class ImageTableViewCell: UITableViewCell {
    @IBOutlet var img1: ExtendedButton!
    @IBOutlet var img2: ExtendedButton!
}

Upvotes: 0

Views: 350

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100503

The problem is in using

let imageData = try? Data(contentsOf: imageURL!)

that blocks the current main thread not because of tableView.reloadData() , you better use SDWebImage

Upvotes: 1

Related Questions