如何在swift中实现相机

时间:2018-04-26 23:26:37

标签: swift xcode uiimagepickercontroller

按下相机按钮时,我的应用程序始终崩溃。当我按下相机按钮时,我试图让相机出现在我的屏幕上。

@IBAction func ACPressed(_ sender: Any) {
    let picker = UIImagePickerController()

    picker.delegate = self
    picker.sourceType = .camera

    present(picker, animated: true, completion: nil)
}

private func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String :AnyObject] ){        
    camera.image = info [UIImagePickerControllerOriginalImage] as? UIImage; dismiss(animated: true, completion: nil)
}

2 个答案:

答案 0 :(得分:0)

这可能是一个模拟器问题。如果要添加代码来处理这种情况,可以执行以下操作:

    if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.camera) {
        let imagePicker = UIImagePickerController()
        imagePicker.delegate = self
        imagePicker.sourceType = UIImagePickerControllerSourceType.camera
        imagePicker.allowsEditing = false
        self.present(imagePicker, animated: true, completion: nil)
    }

通过将其包装在“isSourceTypeAvailable”中,它将避免崩溃。您可以在其中添加else语句并显示通知该问题的警报消息。

答案 1 :(得分:-1)

不要使用模拟器来测试相机。使用真实设备。 您将看到异常的另一种方式:

  

***由于未捕获的异常终止应用' NSInvalidArgumentException',原因:'源类型1不可用'

class ViewController:UIViewController, UIImagePickerControllerDelegate {

    private var imagePicker    : UIImagePickerController!
    private var photo: UIImage?

    @IBAction func ACPressed(_ sender: Any) {
        imagePicker            = UIImagePickerController()
        imagePicker.delegate   = self
        imagePicker.sourceType = .camera
        present(imagePicker, animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        imagePicker.dismiss(animated: true, completion: nil)
        photo = info[UIImagePickerControllerOriginalImage] as? UIImage

    }
}
  

不要忘记设置"隐私 - 相机使用说明"在你的   的Info.plist

我不知道为什么我的答案被downvoted但是在真实设备上尝试这个代码,你会看到代码完美无缺!