Search code examples
swiftxcodeuiimagepickercontroller

UIImagePickerController crashes with LongPressGesture


Today I realized that my UIImagePickerController is working fine when I use it with a button to present it. However, when I want to present it via LongPressGesture, the app crashes on runtime. Why so?

Action:

@IBAction func ppLongPressed(_ sender: UILongPressGestureRecognizer) {
    imagePicker.delegate = self
    imagePicker.sourceType = .photoLibrary
    present(imagePicker, animated: true, completion: nil)
}

Delegate:

func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
        self.profileImage.image = image

    }
    dismiss(animated: true, completion: nil)
}

Solution

  • The long gesture has states

    @IBAction func ppLongPressed(_ sender: UILongPressGestureRecognizer) {
        if sender.state != .began { return }
        imagePicker.delegate = self
        imagePicker.sourceType = .photoLibrary
        present(imagePicker, animated: true, completion: nil)
    }