Md. Monir-Uz-Zaman Md. Monir-Uz-Zaman - 10 days ago 10
Swift Question

update/reload collection view after deleting item from UICollectionView

I have used a collection view of photos for my app.
I have easily deleted items from the collection view but it does not instantly remove the items from collection view. if I go to another view controller and back to collection view controller then its become updated and removed the deleted items from collection view. I want the collection view to be updated instantly when delete operation occurs. How can I solve this problem? Thanks in advance.
My swift code is given below:

import UIKit
import Photos

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate{

var assetCollection: PHAssetCollection = PHAssetCollection()
var photosAsset: PHFetchResult!
var assetThumbnailSize:CGSize!
var selectedIndexPath = [NSIndexPath]()

@IBAction func deleteButton(sender: UIButton) {

if selectedIndexPath.count != 0{

PHPhotoLibrary.sharedPhotoLibrary().performChanges({
//Delete Photo
if let request = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection){
for a in self.selectedIndexPath{
request.removeAssets([self.photosAsset[a.item]])

}
}
}, completionHandler: nil)}


self.collectionView.reloadData()
}


Here is my viewWillAppear method:

override func viewWillAppear(animated: Bool) {

// Get size of the collectionView cell for thumbnail image
if let layout = self.collectionView.collectionViewLayout as? UICollectionViewFlowLayout{
let cellSize = layout.itemSize
self.assetThumbnailSize = CGSizeMake(cellSize.width, cellSize.height)
}

self.photosAsset = PHAsset.fetchAssetsInAssetCollection(self.assetCollection, options: nil)


if let photoCnt = self.photosAsset?.count{
if(photoCnt == 0){
self.noPhotosLabel.hidden = false
}else{
self.noPhotosLabel.hidden = true
}
}

self.collectionView.reloadData()

}

Answer

You need to add the reload method in your completion handler.

    PHPhotoLibrary.sharedPhotoLibrary().performChanges({
                //Delete Photo
                if let request = PHAssetCollectionChangeRequest(forAssetCollection: self.assetCollection){
                    for a in self.selectedIndexPath{
                    request.removeAssets([self.photosAsset[a.item]])

                }
                }
                }, completionHandler: { _ in  
  self.photosAsset = PHAsset.fetchAssetsInAssetCollection(self.assetCollection, options: nil)
  dispatch_async(dispatch_get_main_queue(), { self.collectionView.reloadData() }) 
  })