【问题标题】:UIImagePickerController camera not working swiftUIImagePickerController 相机无法快速工作
【发布时间】:2015-10-08 14:22:18
【问题描述】:

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

这是我的代码:

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

我似乎找不到问题,有人可以帮助我吗?当我尝试运行它并点击拍照时程序崩溃。

【问题讨论】:

  • 发生了什么?它会崩溃吗?什么都没有发生吗?请始终提供正在发生的事情,而不仅仅是“不工作”
  • 我刚刚做了,我很抱歉。
  • 请提供更多关于什么错误的信息?因什么错误而崩溃?有什么记录吗?
  • 如果你使用模拟器,它总是会崩溃。

标签: ios swift uiimagepickercontroller


【解决方案1】:

您很可能在模拟器中运行。模拟器没有摄像头,所以按下按钮时不会导致应用崩溃,您必须检查 cemera 是否可用。

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

【讨论】:

    【解决方案2】:

    按照下面的代码进行

    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】:

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

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

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

      这解决了我的崩溃问题!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-07-22
        • 2013-08-22
        • 1970-01-01
        • 2015-08-21
        • 1970-01-01
        • 2022-12-01
        • 2018-04-13
        • 2023-03-09
        相关资源
        最近更新 更多