selecting multiple images and storing them to coredata

Viewed 356

Iam using PHPickerViewController to load multiple images and store them to CoreData.

Along with the imagepicker, there are three more parameters, which are successfully passed from a previous tableview on tapping its cell.

In coredata i have created an additional parameter galleryImage, of type NSObject to pass this images as array

//button tap to select picker
  @IBAction func gallerySelectClicked(_ sender: Any) {
    
        presentPickerView()
        
    }

//configure


    func presentPickerView() {
        var config : PHPickerConfiguration = PHPickerConfiguration()
        config.selectionLimit = 10
        config.filter = PHPickerFilter.images

        let pickerViewController = PHPickerViewController(configuration: config)
        pickerViewController.delegate = self
        self.present(pickerViewController, animated: true, completion: nil)
    }

//Saving

    func picker(_ picker: PHPickerViewController, didFinishPicking results: [PHPickerResult]) {
        
       picker.dismiss(animated: true, completion: nil)
       
       for item in results {
          item.itemProvider.loadObject(ofClass: UIImage.self, completionHandler: { (image, err) in
             if let image = image as? UIImage {
                print(image)
                DispatchQueue.main.async {
                    self.Gallery.image = image
                    let dh = DatabaseHandler()

//Databasehandler in another file
                    dh.imgArray.append(image)
                    dh.saveImage()

                }
             }
          })
       }
    }

Saveimage function in Databasehandler

 func saveImage() {
        let appDe = (UIApplication.shared.delegate) as! AppDelegate
        let context = appDe.persistentContainer.viewContext
        let photo = NSEntityDescription.insertNewObject(forEntityName: "People", into: context) as! People

       var CDataArray = NSMutableArray();

        for img in imgArray{
            let data : NSData = NSData(data: img.jpegData(compressionQuality: 1)!)
            CDataArray.add(data);
        }

   
        photo.galleryImage = NSKeyedArchiver.archivedData(withRootObject: CDataArray) as NSObject;
        
        do{
            try context.save()
            print("data saved" )
            
        } catch{
            print("error")
        }
        
        
    }

Problem is when I select 2 images and print count to check wheather it is saved, output will be 2. when I select another 2 images in a second run, output is 4 . In this way, count keeos increasing

Could you please help me to find whats wrong with this code? I couldnt find any other good reference for PHPickerController .

0 Answers
Related