Search code examples
swiftuikituiimagepickercontroller

How to make UIImagePickerController for photo library and my problem


I use UIImagePickerController and I want my application to allow me to select a photo from photo library.
I have an interface screen:

enter image description here

I have Image view and I want the gallery to open when I click on the image view. Next, I selected a picture and it was inserted into this circle.

After I select a picture in photo library and my picture is not displayed in the circle. Please help me :(

My code:

import UIKit

class ProfileSettingsViewController: UIViewController,UINavigationControllerDelegate, UIImagePickerControllerDelegate {

  @IBOutlet weak var cancelButton: UIButton!
  @IBOutlet weak var uploadNewPhoto: UIImageView!


  override func viewDidLoad() {
    super.viewDidLoad()
    //    installCancelButtonColor()
    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ProfileSettingsViewController.imageTapped(gesture:)))
    uploadNewPhoto.addGestureRecognizer(tapGesture)
    uploadNewPhoto.isUserInteractionEnabled = true
  }

  @objc func imageTapped(gesture: UIGestureRecognizer) {
    // if the tapped view is a UIImageView then set it to imageview
    if (gesture.view as? UIImageView) != nil {
      print("Image Tapped")
      let imageC = UIImagePickerController()
      imageC.delegate = self
      imageC.sourceType = UIImagePickerController.SourceType.photoLibrary
      present(imageC, animated: true)

    }
  }

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

      guard let image = info[.editedImage] as? UIImage else {
          print("No image found")
          return
      }

      // print out the image size as a test
      print(image.size)
  }

  //  func installCancelButtonColor() {
  //    cancelButton.layer.borderWidth = 1.5
  //    let cancelButtonColor = UIColor(red: 0.20, green: 0.28, blue: 0.36, alpha: 1)
  //    cancelButton.layer.borderColor = cancelButtonColor.cgColor
  //  }


  @IBAction func cancelButton(_ sender: Any) {
    dismiss(animated: true, completion: nil)
  }
}

Solution

  • To see the image in your UIImageView you need to set it up.

     if let image = info[.editedImage] as? UIImage {
         uploadNewPhoto.image = image
     }
    

    If you're not getting the image from didFinishPickingMediaWithInfo try replacing .editedImage with .originalImage

    And will be good to specify when you open PhotoLibrary this

    imageC.mediaTypes = ["public.image"] // this will allow the user to see and select photos only