Search code examples
iosswiftcamerauiimagepickercontrollergallery

UIImagePickerController opening as .camera instead of .savedPhotosAlbum


I am using these two separate buttons in order to open either the camera OR the imageGallery. enter image description here

@IBAction func tapGal(_ sender: Any) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.allowsEditing = true

        self.present(imagePicker, animated: true, completion: nil)

    } else {
        NSLog("No Cam Fam")
    }
}

@IBAction func tapCam(_ sender: Any) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.allowsEditing = true

        self.present(imagePicker, animated: true, completion: nil)

    } else {
        NSLog("No Cam Fam")
    }
}

The Camera button is working just as it should, meaning it opens the camera, but the gallery button is also opening the camera. I have double-checked to make sure that the gallery button is actually linked to the tapGal function. I have also tried replacing .savedPhotosAlbum with .photoLibrary, but the result was the same.


Solution

  • Try replacing your method with new one.

    Your mistake is you have passed same line of code for both method :

    imagePicker.sourceType = UIImagePickerControllerSourceType.camera
    

    instad of

    imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
    

    Replace below method with your one :-

    @IBAction func tapGal(_ sender: Any) {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.savedPhotosAlbum) {
            let imagePicker = UIImagePickerController()
            imagePicker.delegate = self
            imagePicker.sourceType = UIImagePickerControllerSourceType.savedPhotosAlbum
    
    
    
            imagePicker.allowsEditing = true
    
            self.present(imagePicker, animated: true, completion: nil)
    
        } else {
            NSLog("No PhotoLibrary")
        }
    }