Populating UICollection with images via Core Data get blank cell image
Populating UICollection with images via Core Data get blank cell image
Hi I currently have the following flow:
UIImagePickerController
Core Data
UICollectionView
UICollectionView
My issue is that I randomly get images loaded and sometimes I dont get any, do I need to set a delay for the view so it can fetch all the images?
PictureViewController
class PictureViewController: UIViewController {
@IBOutlet weak var collectionView: UICollectionView!
let reuseIdentifier = "CellIdentifier"
var imageObj: [Image] =
let appDelegate = UIApplication.shared.delegate as! AppDelegate
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
fetchData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func fetchData() {
// Setup fetch data
let container = appDelegate.persistentContainer
let context = container.viewContext
let fetchRequest = NSFetchRequest<Image>(entityName: "Image")
do {
// Retrieve array of all images entities in core data
let images = try context.fetch(fetchRequest)
print("COUNT IS ",images.count)
// For each image entity get the imageData from filepath and assign it to image view
for image in images {
imageObj.append(image)
}
} catch {
print("entered catch for image fetch request")
}
} }
extension PictureViewController: UICollectionViewDelegate, UICollectionViewDataSource {
//UICollectionViewDatasource methods
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.imageObj.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath as IndexPath) as! ImagesViewCell
let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
let nsUserDomainMas = FileManager.SearchPathDomainMask.userDomainMask
let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMas, true)
let imageURL = URL(fileURLWithPath: imageObj[indexPath.row].filePath!)
let image = UIImage(contentsOfFile: imageURL.path)
cell.vaultImageView.image = image
return cell
}
}
ViewCell
class ImagesViewCell: UICollectionViewCell {
@IBOutlet weak var vaultImageView: UIImageView!
}
This is the random stuff I get

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.