简体   繁体   中英

Errors while building a custom camera App in swift 2.0

I am building a custom camera application with a custom view for the camera. On adding the following code in the ViewWillAppear section I get the following error in the area I added the stars in: Binary operator '!=' cannot be applied to operands of type 'Bool' and 'NilLiteralConvertible'

Any help is greatly appreciated.

captureSession = AVCaptureSession()
        captureSession.sessionPreset = AVCaptureSessionPreset1920x1080

        let backCamera = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)

        var error : NSError?
        var input: AVCaptureDeviceInput!

        do {
            input = try AVCaptureDeviceInput(device: backCamera)
        } catch let error1 as NSError {
            error = error1
            input = nil
        }

if error == nil && captureSession.canAddInput(input) != nil { *********

                captureSession.addInput(input)

                stillImageOutPut = AVCaptureStillImageOutput()
                stillImageOutPut.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]

                if (captureSession.canAddOutput(stillImageOutPut) != nil){
                    captureSession.addOutput(stillImageOutPut)

                    previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
                    previewLayer.videoGravity = AVLayerVideoGravityResizeAspect
                    previewLayer.connection.videoOrientation = AVCaptureVideoOrientation.Portrait
                    cameraView.layer.addSublayer(previewLayer)
                    captureSession.startRunning()

                }


            }

captureSession.canAddInput(input) returns a Bool , so there is no need to check != nil . Your if statement can become:

if error == nil && captureSession.canAddInput(input) {

Also, you declared input as AVCaptureDeviceInput! . The ! means that it shouldn't ever be nil, but then if there is an error you assign nil to it. This will crash if there is ever an error. You should declare input as AVCaptureDeviceInput? and unwrap input where necessary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM