0

I'm very new to Xcode and Swift, and I was trying to display an image in a UIImageView that was selected using UIImagePickerController. I linked the UIImageView using an @IBOutlet and I put some if statements at the bottom to allow for editing of the selected picture, but I got stuck when an error popped up in my code. I'm pretty sure that the problem has something to do with how I am referencing the UIImageView, but I don't know how to do it in a different way. I just got this account to ask this question, so forgive me for the way I made this post.

Here is the code:

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
    }

    @IBAction func openPhotosButton(_ sender: UIButton) {
        showImagePickerController()
    }

    @IBOutlet weak var characterView: UIImageView!

}

extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    func showImagePickerController() {
        let imagePickerController = UIImagePickerController()
        imagePickerController.delegate = self
        imagePickerController.allowsEditing = true
        imagePickerController.sourceType = .photoLibrary
        present(imagePickerController, animated: true)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as UIImage {
            characterView.image = editedImage
        }
        else if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as UIImage {
            characterView.image = originalImage
        }

        dismiss(animated: true)
    }
}

Picture from Xcode:

picture from Xcode

TylerP
  • 9,600
  • 4
  • 39
  • 43
Liam
  • 65
  • 1
  • 4
  • Does this answer your question? [How to allow user to pick the image with Swift?](https://stackoverflow.com/questions/25510081/how-to-allow-user-to-pick-the-image-with-swift) – Harry J May 19 '20 at 23:44

1 Answers1

0

change your method to this one

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {

        if let editedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
            characterView.image = editedImage
        }
        else if let originalImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            characterView.image = originalImage
        }

        dismiss(animated: true)
    }
Jawad Ali
  • 13,556
  • 3
  • 32
  • 49
  • Thank you so much! This worked like a charm! So the change was that I have to use the '.InfoKey' and us 'as?' instead of 'as'? – Liam May 19 '20 at 23:58
  • I'm also trying to make this app upload multiple photos and organize them in a kind of album. Any quick tips or specific classes I could use? – Liam May 20 '20 at 00:05