0

I have a UICollectionView, it runs as it should when I add fixed data to it, but if I reloaded it again (getting data from service) the scroll becomes slow or it might stop scrolling.

This is the code:

@IBOutlet var myCollectionView: UICollectionView!

func getAllCategories() {
        API.categories { (error: Error?, success: Bool,  categories: [Category]) in
            if success {
                self.categories = categories
                print("success")
                self.myCollectionView.reloadData()
            } else {
                print("failed")
            }
        }
    }

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if(self.categories.count > 0) {
            return (self.categories.count - 1)
        } else {
            return 0
        }
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HomeCollectionViewCell", for: indexPath) as! HomeCollectionViewCell

        cell.containerCollectionView.layer.cornerRadius = 20
        cell.containerCollectionView.layer.borderWidth = 2
        cell.containerCollectionView.layer.borderColor = UIColor(red:219/255.0, green:219/255.0, blue:219/255.0, alpha: 0.5).cgColor;
        cell.containerCollectionView.layer.masksToBounds = true
        if(self.categories.count > 0) {
            cell.category_name.text = self.categories[indexPath.row + 1].name
            cell.adds_number.text = String(self.categories[indexPath.row + 1].ads_count) + " إعلان"
            cell.fav_number.text = String(self.categories[indexPath.row + 1].fav_count) + " مفضلة"
            ////// to load URLs images //////
                let imageUrl = "http://xxxxxxxx.com/images/categories/" + self.categories[indexPath.row + 1].image
                let url = URL(string: imageUrl)
                let image = NSData(contentsOf: url!)
                if(image != nil){
                    cell.categoryImageView.image = UIImage(data: image! as Data)
                }
        }
        return cell
    }

Any solution for my case?

iDeveloper
  • 2,339
  • 2
  • 24
  • 38
Al-shimaa Adel
  • 767
  • 1
  • 10
  • 26
  • Related: https://stackoverflow.com/questions/36570745/uiimage-from-url-takes-long-time-to-load-swift https://stackoverflow.com/questions/24231680/loading-downloading-image-from-url-on-swift https://stackoverflow.com/questions/37018916/swift-async-load-image/37019507 – Ahmad F Mar 04 '18 at 09:11

2 Answers2

1

The problem is here

 let image = NSData(contentsOf: url!)

this should be in DispatchQueue.global.async not main , as this line blocks the mainQueue until data of the image fetched from the url , this causes a delay in loading the collectionView

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • hey @Sh_Khan, I wonder, what's the effect of that not using NSData in `globalQuoeu`, also you mean `DispatchQueoe.async` right ? – eemrah Mar 04 '18 at 09:10
  • 1
    this causes a delay as it blocks the main queue from returning the cells lastly – Shehata Gamal Mar 04 '18 at 09:13
  • ok, cool. I'm wondering will it cool to using `didSet` for `categories`categories array, so when a data is append to array, use `DispatchQueue.global.async` and reload data as you mentioned before. – eemrah Mar 04 '18 at 09:18
  • didSet can be used to write only one reloadData inSide it instead of spreading it in all the code where the array changes but to run in DispatchQueue.main.async – Shehata Gamal Mar 04 '18 at 09:22
1

The problem at below code:

////// to load URLs images //////
            let imageUrl = "http://souqsahm.com/images/categories/" + self.categories[indexPath.row + 1].image
            let url = URL(string: imageUrl)
            let image = NSData(contentsOf: url!)
            if(image != nil){
                cell.categoryImageView.image = UIImage(data: image! as Data)
            }

try fo download the image in background thread, or you can using this api https://github.com/rs/SDWebImage

Moayad Al kouz
  • 1,342
  • 1
  • 9
  • 19