UIImagePickerController camera not working swift

谁说胖子不能爱 提交于 2019-12-08 02:20:01

问题


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.


回答1:


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



回答2:


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



回答3:


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!



来源:https://stackoverflow.com/questions/33018529/uiimagepickercontroller-camera-not-working-swift

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