UIImagePickerController camera not working swift

狂风中的少年 提交于 2019-12-06 04:38:16

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

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.")
}
Fidel

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!