如何保存从UIPickerController中挑选的多个图像?

时间:2018-03-23 15:24:37

标签: swift uicollectionview nsuserdefaults

我在应用中上传的所有图片(UIImagePickerController)都会显示在应用中,但是当我关闭应用时,图片就会消失。我将UserDefaults用于一个图像(没有UICollectionView)并且代码工作(请参阅代码)但是当我使用UICollectionView时,代码不再起作用。如果有人可以帮助我或给我一些提示,那将是很好的!

import UIKit

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

    @IBOutlet weak var allImagesCollection: UICollectionView!

    var collectionViewClass = CollectionViewCell()
    var theUploadedImg =  UIImageView()

    let userDefault = UserDefaults.standard

    override func viewDidLoad() {
        super.viewDidLoad()

        allImagesCollection.delegate = self
        allImagesCollection.dataSource = self

        collectionViewClass.newImage = theUploadedImg

        let imageData = userDefault.object(forKey: "thePickedImage") as? NSData
        if let imageData = imageData {
            let image = UIImage(data: imageData as Data)
            theUploadedImg.image = image
        }

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

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

    @IBAction func chooseImage(_ sender: Any) {
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self

        let actionSheet = UIAlertController(title: "", message: "Choose an image from", preferredStyle: .actionSheet)

        actionSheet.addAction(UIAlertAction(title: "Camera", style: .default, handler: { (action: UIAlertAction) in

            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
                imagePickerController.sourceType = UIImagePickerControllerSourceType.camera
                imagePickerController.allowsEditing = false
                self.present(imagePickerController, animated: true, completion: nil)
            }
        }))

        actionSheet.addAction(UIAlertAction(title: "Photo Library", style: .default, handler: { (action: UIAlertAction) in

            if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
                imagePickerController.sourceType = UIImagePickerControllerSourceType.photoLibrary
                imagePickerController.allowsEditing = false
                self.present(imagePickerController, animated: true, completion: nil)
            }
        }))

        actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
        self.present(actionSheet, animated: true, completion: nil)

    }

    var newPickedImage = [UIImage]()

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let pickedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            theUploadedImg.contentMode = .scaleToFill
            theUploadedImg.image = pickedImage

            newPickedImage.append(pickedImage)


            let pickedImageData = UIImagePNGRepresentation(pickedImage)
            userDefault.set(pickedImageData, forKey: "thePickedImage")
        }
        picker.dismiss(animated: true, completion: nil)
        allImagesCollection.reloadData()
   }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return newPickedImage.count
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
        cell.newImage.image = newPickedImage[indexPath.item]

        cell.layer.borderColor = UIColor.lightGray.cgColor
        cell.layer.borderWidth = 0.5

        return cell
    }

    let cellsPerRow = 3

    override func viewWillLayoutSubviews() {
        guard let collectionView = allImagesCollection, let flowLayout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return }
        let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + collectionView.safeAreaInsets.left + collectionView.safeAreaInsets.right + flowLayout.minimumInteritemSpacing * CGFloat(cellsPerRow - 1)
        let itemWidth = ((collectionView.bounds.size.width - marginsAndInsets) / CGFloat(cellsPerRow)).rounded(.down)
        flowLayout.itemSize =  CGSize(width: itemWidth, height: itemWidth)
    }


}

1 个答案:

答案 0 :(得分:1)

您只将1张图片保存到UserDefaults。为了保留这些图像,您必须保存所有图像,而不是仅覆盖1个图像。此外,在应用程序启动时,您必须获取所有图像并使用它们重新加载UICollectionView。 还有一个提示,请勿将图片保存到UserDefaults,请使用FileManager