如何正确启动iPhone相机

时间:2019-05-24 18:17:04

标签: ios swift camera

我正在尝试构建一个简单的应用程序,该应用程序将扫描条形码并具有这段代码

var captureSession: AVCaptureSession?
var videoPreviewLayer: AVCaptureVideoPreviewLayer?
var codeView: UIView?

override func viewDidLoad() {
    super.viewDidLoad()

    let discoverySession = AVCaptureDevice.DiscoverySession(deviceTypes: [.builtInDualCamera], mediaType: AVMediaType.video, position: .back)
    guard let captureDevice = discoverySession.devices.first else {
        print("Camre initialization faild.")
        return
    }
    do {
        let input = try AVCaptureDeviceInput(device: captureDevice)
        captureSession?.addInput(input)

        let captureMetadataOutput = AVCaptureMetadataOutput()
        captureSession?.addOutput(captureMetadataOutput)
        captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]

        videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession!)
        videoPreviewLayer?.videoGravity = AVLayerVideoGravity.resizeAspectFill
        videoPreviewLayer?.frame = view.layer.bounds
        view.layer.addSublayer(videoPreviewLayer!)
        captureSession?.startRunning()

    } catch let error as NSError {
        print("Error \(error.localizedDescription)")
    }

}

我在装有iOS 12.3.1的物理设备Xs Max上运行应用程序,并且意外崩溃了

 captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]

错误“ libc ++ abi.dylib:以类型为NSException的未捕获异常终止”

1 个答案:

答案 0 :(得分:0)

UITabBarController

此代码应该可以为您提供帮助,还请记住添加AVCaptureMetadataOutputObjectsDelegate