0

I am trying to create an application that has two collection views in one. I want to first populate the first collection view, and then the second. First, I set the delegate of photoCollectionView to self. Then, I populated the collectionview by calling photoCollectionView.reloadData(). However, I want photoCollectionView.reloadData() to first complete before any further code is executed because when I included the code underneath it, the collection view I was initially trying to populate doesn't populate. However, when I remove the code, it does populate. I tried to use DispatchQueue, but I had no luck.

photoCollectionView.dataSource = self
photoCollectionView.reloadData() // I want this code to complete before executing anything else under it.

media.removeAll()

let assetVideo = PHAsset.fetchAssets(with: PHAssetMediaType.video , options: nil)
assetVideo.enumerateObjects({ (object, count, stop) in
    self.media.append(object)
})

self.media.reverse()

videoControllerView.dataSource = self
videoControllerView.reloadData()

Code after adding DispatchQueue. When executing this code, the collection view does not populate. However, if we comment out all the code in the DispatchQueue, it populates.

photoCollectionView.dataSource = self
photoCollectionView.reloadData()

DispatchQueue.main.async {
    self.media.removeAll()

    let assetVideo = PHAsset.fetchAssets(with: PHAssetMediaType.video , options: nil)
    assetVideo.enumerateObjects({ (object, count, stop) in
        self.media.append(object)
    })

    self.media.reverse()

    self.videoControllerView.dataSource = self
    self.videoControllerView.reloadData()
}

Any help is appreciated. Thanks!

itsfaraaz
  • 191
  • 2
  • 14

1 Answers1

0

reloadData unfortunately does not have a completion handler, but it's relatively easy to achieve the same effect by putting the call into a CATransaction block.

CATransaction.begin()
CATransaction.setCompletionBlock {
    // this runs after reloadData is done
}
photoCollectionView.reloadData()
CATransaction.commit()
Gereon
  • 17,258
  • 4
  • 42
  • 73
  • Do you mean `photoCollectionView.reloadData()` instead of `self.media.removeAll()`? Also, `CATransaction.setCompletionHandler` does not exist. – itsfaraaz Apr 07 '18 at 20:24
  • Sorry, I meant `photoCollectionView.reloadData() ` (whatever the first reloadData is you want to wait for) and `setCompletionBlock`. Updated my answer. – Gereon Apr 07 '18 at 20:45
  • Okay so just to clarify, the code within `CATransaction.setCompletionBlock` runs after `photoCollectionView.reloadData()` is complete? – itsfaraaz Apr 07 '18 at 20:50
  • Yes. See https://stackoverflow.com/questions/16071503/how-to-tell-when-uitableview-has-completed-reloaddata (last answer) for a nice example of how this can be made into an extension. – Gereon Apr 07 '18 at 21:06