UIImagePickerController 相机不工作 swift

UIImagePickerController camera not working swift

我有一个操作 sheet,它有两个选项:一个是您可以从您的图库中选择一张图片,另一个是您可以从相机拍摄一张照片。照片库功能正常,但我似乎无法让相机工作。

这是我的代码:

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

我好像找不到问题,谁能帮帮我?当我尝试 运行 并单击“拍照”时程序崩溃。

按照下面的代码

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

您很可能 运行 在模拟器中。模拟器没有摄像头,因此在按下按钮时不会使应用程序崩溃,您必须检查 cemera 是否可用。

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

正如 Kirit Modi 在下面所说的那样,相机在真实设备中使用时会崩溃的另一个原因是:

在iOS 10.您必须为相机和照片库设置隐私设置。 info.Plist

的相机和照片隐私设置

这解决了我的崩溃问题!