2

我正在使用PHPickerViewController加载多个图像并将它们存储到 CoreData。

除了 imagepicker 之外,还有另外三个参数,这些参数在点击其单元格时从先前的 tableview 成功传递。

在 coredata 中,我创建了一个附加参数galleryImage,类型NSObject为将此图像作为数组传递

//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作用于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")
        }
        
        
    }

问题是当我选择 2 张图像并打印计数以检查是否保存时,输出将为 2。当我在第二次运行中选择另外 2 张图像时,输出为 4 。这样,count keeos 就会增加

你能帮我找出这段代码有什么问题吗?我找不到 PHPickerController 的任何其他好的参考。

4

0 回答 0