UICollectionView不加载图像

时间:2018-06-30 19:51:19

标签: ios core-data uicollectionview

我使用Core Data设置了一个数据库,用户可以在其中保存图像,这些图像以路径方式存储,我有一个视图,我想在其中使用我的单元格加载这些图像,但是图像不会加载。我是新手,我搜索了很多,但是找不到为什么会发生的答案,请提出建议。

尝试此操作的最初方法是在项目中设置图片文件夹,然后实际加载这些图片,但是当我尝试使用URL方法时,它们将不会加载。

视图控制器

import UIKit
import CoreData

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {

    @IBOutlet weak var collectionView: UICollectionView!
    let appDelegate = UIApplication.shared.delegate as! AppDelegate

//    let array: [String] = ["1","2","3","4","5","6"]
    var array: [Image] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        let numberOfColumns: CGFloat = 2
        if let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
            let horizontalSpacing = flowLayout.scrollDirection == .vertical ? flowLayout.minimumInteritemSpacing : flowLayout.minimumLineSpacing
            let cellWidth = (collectionView.frame.width - max(0, numberOfColumns - 1)*horizontalSpacing)/numberOfColumns
            flowLayout.itemSize = CGSize(width: cellWidth, height: cellWidth)

            collectionView.collectionViewLayout = flowLayout
        }

        fetchData()
        print("did load")


    }
    override func viewWillAppear(_ animated: Bool) {
        print("WILL APPER")
        collectionView.reloadData()
    }

//    func fetchData() {
//        print("data fetch")
//        let appDelegate = UIApplication.shared.delegate as! AppDelegate
//        let container = appDelegate.persistentContainer
//        let context = container.viewContext
//        let fetchRequest = NSFetchRequest<Image>(entityName: "Image")
//        fetchRequest.returnsObjectsAsFaults = false
//
//        do {
//            let results = try context.fetch(fetchRequest)
//            array = results as [Image]
//        } catch let error as NSError {
//            print("Could not fetch \(error), \(error.userInfo)")
//        }
//    }
    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 {
                array.append(image)
            }
        } catch {
            print("entered catch for image fetch request")
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // Number of views
    // How many items we want, the same as the amout of data we want to display
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        print("array count")
        print(array.count)
        return array.count
    }

    // Populate the views with the images
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! ImageCellController
        let imageURL = URL(fileURLWithPath: array[indexPath.row].fullPath!)
        print(array[indexPath.row].fullPath)
        let image = UIImage(contentsOfFile: imageURL.path)
        cell.imageViewCell.image = image
        //        print(array[indexPath.row])
//        cell.imageViewCell.image = UIImage(named: array[indexPath.row] + ".JPG")
//        return cell

        return cell
    }

}

图像单元控制器

class ImageCellController: UICollectionViewCell {

    @IBOutlet weak var imageViewCell: UIImageView!
}

按钮视图控制器

class ButtonsViewController: UIViewController {
    @IBOutlet weak var uploadButtn: UIButton!
    let imagePicker = UIImagePickerController()
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    var managedObjectContext: NSManagedObjectContext? = nil

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func uploadAction(_ sender: Any) {
        let myPickerController = UIImagePickerController()
        myPickerController.delegate = self
        myPickerController.sourceType = .photoLibrary
        present(myPickerController, animated: true, completion: nil)


    }
}

extension ButtonsViewController:  UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {

            // Get the access to shared instance of the file manager
            let fileManager = FileManager.default

            // Get the URL for the users home directory
            let documentsURL = fileManager.urls(for: .documentDirectory, in: .userDomainMask).first!
            print("Documents url: ", documentsURL)

            //Get the document url as a string
            let documentPath = documentsURL.path
            print("Document path is ", documentPath)
            let diceRoll = Int(arc4random_uniform(50) + 1)
            // Create a filePath URL by appending final path component (name of img)
            let filePath = documentsURL.appendingPathComponent("uploadedImage\(String(diceRoll)).png")
            print("File path is: ", filePath)

            do {
                if let pngImageData = UIImagePNGRepresentation(pickedImage) {
                    try pngImageData.write(to: filePath, options: .atomic)
                }
            } catch {
            }

            // Save filepath to CoreData
            let container = appDelegate.persistentContainer
            let context  = container.viewContext
            let entity =  Image(context: context)
            entity.fullPath = filePath.path

            appDelegate.saveContext()
        }

        dismiss(animated: true, completion: nil)
    }

    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
}

1 个答案:

答案 0 :(得分:1)

在for循环之后尝试collectionView.reloadData(),将图像追加到数组。