iosswiftnsexceptionphotolibrary

Present ImagePickerView causing crash


Here is my code, a simple class with a view created in storyboard that contains a button to present the imagePickerView. The imagePickerView gets presented and then the app crashes with libc++abi.dylib: terminating with uncaught exception of type NSException

import Foundation
import UIKit


class ImageSelectionView: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {


override func viewDidLoad(){
    super.viewDidLoad()
}

@IBAction func backButtonTapped(_ sender: AnyObject) {
    self.navigationController?.dismiss(animated: true, completion: nil)
}


@IBAction func openPhotoLibrary(_ sender: AnyObject) {
    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary;
        imagePicker.allowsEditing = true
        present(imagePicker, animated: true, completion: nil)
        self.present(imagePicker, animated: true, completion: nil)
    }
}


func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    self.dismiss(animated: true, completion: nil);
}




}

Can't figure out where this is going wrong, any help would be awesome, thank you!


Solution

  • For accessing photo library, you need to put Privacy - Photo Library Usage Description in your application's .plist file with some description,

    like this shown in image

    enter image description here

    And porticularly in your code, you have written code to present the same imagePicker twice as showing below.

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

    Hence I suggest to keep one, may be
    present(imagePicker, animated: true, completion: nil)

    OR

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

    Hope it helps.

    Happy coding ...