嗨,我目前有以下流程:
UIImagePickerController
上传图片(在另一视图中)Core Data
内的路径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!
}
这是我得到的随机物品