フォトライブラリをすばやく選択しても表示されないのはなぜですか?

Dec 09 2020

使用して、この私は、彼らがカメラを使用したり、自分の携帯電話から画像を選択するかどうかを決定するためにユーザに尋ねる質問を:

//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)
    }

私がviewDidLoadそのように呼び起こすもの:

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

ただし、これをテストすると、アラートがポップアップし、フォトライブラリを選択しましたが、ライブラリが表示されません。使ってみましたviewDidAppearが、うまくいきませんでした。エラーは表示されません。アラートを非表示にし、現在のViewControllerを表示するだけです。

回答

1 matt Dec 09 2020 at 00:00

アラートが表示されたときにコードが停止することを想像しているかもしれません。しかし、そうではありません!また、提示された2つのViewControllerを同時に表示することはできません。しかし、それはあなたがやろうとしていることです。

あなたが言っているshowAlert()ので、今あなたのアラートは上がっています、そしてあなたはすぐに言ってpresent(imagePicker)います、あなたのアラートがまだ上がっているのであなたはそれをすることができません。

showAlertアラートのアクションハンドラーを使用して、画像ピッカーを表示します。これにより、アラートが閉じ、画像ピッカーが開きます。