Trenton Tyler
Trenton Tyler

Reputation: 1712

UIImagePickerController camera not working swift

I have an action sheet that has two options: one where you can choose an image from your library and one where you can take a photo from the camera. The photo library functions properly, but I can't seem to get the camera to work.

Here is my code:

let takePhoto = UIAlertAction(title: "Take photo", style: .Default,   handler: {
    (alert: UIAlertAction!) -> Void in
    // present camera taker
    var cameraPicker = UIImagePickerController()
    cameraPicker.delegate = self
    cameraPicker.sourceType = .Camera
    self.presentViewController(cameraPicker, animated: true, completion: nil)   
})

func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
    var selectedAvatar = UIImagePickerControllerOriginalImage
    self.dismissViewControllerAnimated(false, completion: nil)
}

I can't seem to find the problem, can anybody help me out? The program crashes when I try to run it and click on Take Photo.

Upvotes: 2

Views: 5093

Answers (3)

Fidel
Fidel

Reputation: 1183

There is another reason why the camera can crash when used in a real device as Kirit Modi said in the following tread:

iOS 10 - App crashes To access photo library or device camera via UIImagePickerController

In iOS 10. You have to set privacy Setting for Camera & Photo Library. Camera & Photo Privacy Setting at info.Plist

This solved my crashing issue!

Upvotes: 0

Arbitur
Arbitur

Reputation: 39091

You are most likely running in the simulator. The simulator dont have a camera so to not make the app crash when pressing the button you have to check if cemera is available.

if UIImagePickerController.isSourceTypeAvailable(.Camera) {
    ...
}
else {
    print("Sorry cant take picture")
}

Upvotes: 6

user3182143
user3182143

Reputation: 9609

Follow the below code

func takePhoto()
{
  if(UIImagePickerController .isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera))
  {
    picker!.sourceType = UIImagePickerControllerSourceType.Camera
    self .presentViewController(picker!, animated: true, completion: nil)
  }
  else
  {
    let alertWarning = UIAlertView(title:"Warning", message: "You don't have camera", delegate:nil, cancelButtonTitle:"OK", otherButtonTitles:"")
    alertWarning.show()
  }
}
func openGallary()
{
  picker!.sourceType = UIImagePickerControllerSourceType.PhotoLibrary
  self.presentViewController(picker!, animated: true, completion: nil)
}

//PickerView Delegate Methods
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
  picker .dismissViewControllerAnimated(true, completion: nil)
  imageView.image=info[UIImagePickerControllerOriginalImage] as? UIImage
}
func imagePickerControllerDidCancel(picker: UIImagePickerController)
{
  println("picker cancel.")
}

Upvotes: 1

Related Questions