0

I am trying to make a TableView App that allows adding images and names to it using the ImagePickerController and changing its name via an AlertController TextField

The problem is the ImagePicker is not picking up the Image and no error is shown on the debugging console.

When I click the Image to pick it, nothing happens.

class ViewController: UITableViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    var photos = [Photo]()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "Snapshots"
        navigationController?.navigationBar.prefersLargeTitles = true

        navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addPhoto))

        let defaults = UserDefaults.standard

        if let savedPhotos = defaults.object(forKey: "photos") as? Data {
            let jsonDecoder = JSONDecoder()
            do {
                photos = try jsonDecoder.decode([Photo].self, from: savedPhotos)
            } catch {
                print("Failed to load photos.")
            }
        }

    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return photos.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        guard let cell = tableView.dequeueReusableCell(withIdentifier: "Photo", for: indexPath) as? PhotoCell else {
            fatalError("Could not load the Photo Cell")
        }
        let photo = photos[indexPath.row]
        cell.textLabel?.text = photo.name
        let path = getDocumentsDirectory().appendingPathComponent(photo.image)
        cell.imageView?.image = UIImage(contentsOfFile: path.path)

        return cell
    }

    @objc func addPhoto() {
        let picker = UIImagePickerController()
        picker.isEditing = true
        picker.delegate = self
        present(picker, animated: true)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let image = info[.editedImage] as? UIImage else { return }

        let imageName = UUID().uuidString
        let imagePath = getDocumentsDirectory().appendingPathComponent(imageName)

        if let jpegData = image.jpegData(compressionQuality: 0.8) {
            try? jpegData.write(to: imagePath)
        }

        let photo = Photo(name: "New Image", image: imageName)
        photos.append(photo)
        save()
        tableView.reloadData()

        dismiss(animated: true)

    }

    func getDocumentsDirectory() -> URL {
        let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
        return paths[0]
    }

    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

            let photo = photos[indexPath.row]

            let ac = UIAlertController(title: "What you want to do with Image?", message: nil, preferredStyle: .alert)

            ac.addTextField()

            ac.addAction(UIAlertAction(title: "Rename", style: .default) {
                [weak self, weak ac] _ in
                guard let newName = ac?.textFields?[0].text else { return }
                photo.name = newName
                self?.save()
                self?.tableView.reloadData()
            })

            ac.addAction(UIAlertAction(title: "Delete", style: .destructive) {
                [weak self] _ in
                self?.photos.remove(at: indexPath.row)
                self?.tableView.reloadData()
            })

            ac.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

            ac.addAction(UIAlertAction(title: "Open", style: .default) {
                [weak self] _ in
                if let vc = self?.storyboard?.instantiateViewController(withIdentifier: "PhotoView") as? DetailViewController {
                    vc.selectedImage = photo.name
                    self?.navigationController?.pushViewController(vc, animated: true)
                }
            })

            present(ac, animated: true)

    }

    func save() {
        let jsonEncoder = JSONEncoder()
        if let savedData = try? jsonEncoder.encode(photos) {
            let defaults = UserDefaults.standard
            defaults.set(savedData, forKey: "photos")
        } else {
            print("Failed to save photos.")
        }
    }

}
Daniel Espina
  • 614
  • 11
  • 24
  • What do you mean by *"the ImagePicker is not picking up the Image"*? Is the image picker being shown? Is the image picker delegate called when you select an image? – rmaddy Jun 11 '19 at 19:03

2 Answers2

0

I actually took your code and condensed it down quite a bit to test locally and found one possible issue here:

guard let image = info[.editedImage] as? UIImage else { return }

If your user has not edited a photo, then the return kicks in and nothing further happens.

However, if I change it to .originalImage like this, then simply selecting an image will allow it to proceed:

guard let image = info[.originalImage] as? UIImage else { return }

With that said, you may want to consider a switch statement, or some if/else to facilitate different types of images based on whatever suits your app.

CodeBender
  • 35,668
  • 12
  • 125
  • 132
-1

Have you added Photo Library Usage permission in info.plist file? If you havn't then add "Privacy - Photo Library Usage Description " in info.plist.

  • It is not using it, then why should I add –  Jun 11 '19 at 18:54
  • ImagePickerController picks images from your photo library. In order to access the photo library you need to ask for permission. – Rajat Sharma Jun 11 '19 at 18:58
  • @RajatSharma You don't need this privacy setting to use `UIImagePickerController`. – rmaddy Jun 11 '19 at 19:02
  • @rmaddy https://theswiftdev.com/2019/01/30/picking-images-with-uiimagepickercontroller-in-swift-5/ – Rajat Sharma Jun 11 '19 at 19:04
  • @RajatSharma If all you want is the `.originalImage` you do _not_ need user permission. https://stackoverflow.com/a/48413456/341994 – matt Jun 11 '19 at 23:43