Search code examples
iosswiftuicollectionviewcelluiimagepickercontroller

how to get a photo with imagepickercontroller into the collectionView cell as thumbnail


I try to create a code to pick photos from photo album and show it on the screen as thumbnail in the collection view cells. I will pick one photo per a button click and new photo will appear next to previous thumbnail. CollectionView will have single line with vertical scroll. I struggle to transfer the image from pickercontroller didFinishPickingMediaWithInf method into the collectionView cellForItemAt method. I have found out a solution by using a dummy UIImageV but it only shows the first photo not the others. I don't get any crash. could you please help me how to correct the code to upload photos I selected from photo album into the collection view cells. Please see the code below:

class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UIImagePickerControllerDelegate,UINavigationControllerDelegate {

    public let imagePicker = UIImagePickerController()
    
    @IBOutlet weak var dummyImageView: UIImageView!
    
    private let reuseIdentifier = "myViewCell"
    
    var myImage = [UIImage]()
    
    @IBOutlet var collectionView: UICollectionView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        dummyImageView.isHidden = true
        collectionView.dataSource = self
        collectionView.delegate = self
                
    }
        
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return myImage.count    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        
       let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier , for: indexPath) as! MyViewCell
        
        cell.backgroundColor = UIColor.blue
        
        let imageView = cell.myImage
        myImage.append(dummyImageView.image!)
        imageView!.image = myImage[indexPath.row]
        
        return cell
        
    }

    @IBAction func imageButtonPressed(_ sender: Any) {
        
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        imagePicker.allowsEditing = false
         
        self.present(imagePicker, animated: true, completion: nil)
      
       
        }
      

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        
    
        if  let image = info[.originalImage] as? UIImage{
            print("last value",myImage.count)
            
            dummyImageView.image = image
            myImage.append(dummyImageView.image!)
            
            collectionView.reloadData()
           
        
        } else {
            print("error to load")
        }
               
       dismiss(animated: true, completion: nil)    
    }
}

Solution

  • The issue is not obvious so I had to recreate it on my machine. Actually myImage array is getting loaded twice in below functions.

    1. didFinishPickingMediaWithInfo
    2. cellForItemAt

    This causes the data from collection view to get added to the myImage array. Removing the below assignment in cellForItemAt, solves the issue. // myImage.append(dummyImageView.image!)