通过核心数据用图像填充UICollection获取空白单元格图像

时间:2018-06-29 23:16:42

标签: ios swift core-data uicollectionview

嗨,我目前有以下流程:

  1. 用户从UIImagePickerController上传图片(在另一视图中)
  2. 图像存储为Core Data内的路径
  3. 上传图片后,用户将重定向到UICollectionView(从我在第1点到UICollectionView中描述的视图)

我的问题是我随机加载图像,有时却什么也没有,是否需要为视图设置延迟,以便它可以获取所有图像?

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!
}

这是我得到的随机物品

enter image description here

0 个答案:

没有答案