iosswiftphoto-gallery

Why is photo library not displaying when I select it in swift?


Using this question I ask the user to decide whether they want to use the camera or choose an image from their phone:

//Show alert to select the media source type.
    private func showAlert() {

        let alert = UIAlertController(title: "Image Selection", message: "From where you want to pick this image?", preferredStyle: .actionSheet)
        alert.addAction(UIAlertAction(title: "Camera", style: .default, handler: {(action: UIAlertAction) in
            self.imagePicker.sourceType = .camera
        }))
        alert.addAction(UIAlertAction(title: "Photo Album", style: .default, handler: {(action: UIAlertAction) in
            self.imagePicker.sourceType = .photoLibrary
        }))
        alert.addAction(UIAlertAction(title: "Cancel", style: .destructive, handler: nil))
            self.present(alert, animated: true, completion: nil)
    }

Which I envoke in viewDidLoad as such:

override func viewDidLoad() {
        super.viewDidLoad()
        firstTextField.delegate = self
        showAlert()
        present(imagePicker, animated: true, completion: nil)
        imagePicker.delegate = self
        firstImageView.layer.cornerRadius = 8
        
    }

However when I test this the alert pops up and I choose the photo library, but the library does not appear. I have tried using viewDidAppear but that failed to work as well. No errors appear, it just hides the alert and shows the current view controller.


Solution

  • You may be imagining that code comes to a stop when an alert appears. But it doesn't! And you cannot show two presented view controllers simultaneously. But that is what you are trying to do.

    You are saying showAlert(), so now your alert is up, and then you are immediately saying present(imagePicker), which you cannot do because your alert is still up.

    Use the action handlers of the showAlert alert to present the image picker. That way, the alert closes and the image picker opens.