So after i finished chapter 3 and started doing testing my method was something like this
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
if coordinator.session.localDragSession != nil {
collectionView.performBatchUpdates({
for item in coordinator.items {
guard let sourceIndex = item.sourceIndexPath else {
return
}
self.entry?.images.remove(at: sourceIndex.item)
self.collectionView.deleteItems(at: [sourceIndex])
}
})
}
let destinationIndex = coordinator.destinationIndexPath ?? IndexPath(item: 0, section: 0)
coordinator.session.loadObjects(ofClass: UIImage.self) { [weak self] imageItems in
guard let self = self else { return }
let images = imageItems as! [UIImage]
self.entry?.images.insert(contentsOf: images, at: destinationIndex.item)
self.collectionView.performBatchUpdates({
let newIndexPaths = Array(repeating: destinationIndex,count: images.count)
self.collectionView.insertItems(at: newIndexPaths)
})
}
}
I got crashes on self.collectionView.performBatchUpdates({
Looking into finished versions of the book i found this:
func collectionView(_ collectionView: UICollectionView, performDropWith coordinator: UICollectionViewDropCoordinator) {
let destinationIndex = coordinator.destinationIndexPath?.item ?? 0
for item in coordinator.items {
if coordinator.session.localDragSession != nil,
let sourceIndex = item.sourceIndexPath?.item {
self.entry?.images.remove(at: sourceIndex)
}
item.dragItem.itemProvider.loadObject(ofClass: UIImage.self) { (object, error) in
guard let image = object as? UIImage, error == nil else {
print(error ?? "Error: object is not UIImage")
return
}
DispatchQueue.main.async {
self.entry?.images.insert(image, at: destinationIndex)
self.reloadSnapshot(animated: true)
}
}
}
}
I think the the problem is on the way the chapter covers this, if you test and try to do drag/drop finishing chapter 3 the app will crash, please check, seems that other people have problems like this.