二维码扫描自动打开闪光灯

  let videoDataOutput = AVCaptureVideoDataOutput()

            videoDataOutput.setSampleBufferDelegate(self,queue:DispatchQueue.main)

//AVCaptureVideoDataOutputSampleBufferDelegate

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {

        

        let metadataDict = CMCopyDictionaryOfAttachments(nil,sampleBuffer, kCMAttachmentMode_ShouldPropagate);

        let  metadata = metadataDict as![String:Any]

        let  exifMetadata = metadata[kCGImagePropertyExifDictionary as String] as? [String:Any]

        let brightnessValue = exifMetadata![kCGImagePropertyExifBrightnessValue as String]

        print(brightnessValue as Any)

        let valueStr = (brightnessValue as AnyObject).description

        let valueNSStr = NSString.init(string: valueStr!)

        if (valueStr?.contains("-"))! {

            guard self.device?.hasTorch == true else{

                //提示光度不够

                MyAlertLabel.initWith(CGSize.init(width: 100, height: 35), andMessage: "亮度太暗", andViewController: self)

                return

            }

            if  self.device?.torchMode != .on {

                self.session.beginConfiguration()

                try? self.device?.lockForConfiguration()

                try? self.device?.setTorchModeOn(level:0.7)

                self.device?.unlockForConfiguration()

                self.session.commitConfiguration()

            }

        }else if valueNSStr.character(at: 0) == NSString.init(string: "0").character(at: 0){

            guard self.device?.hasTorch == true else{

                //提示光度不够

                MyAlertLabel.initWith(CGSize.init(width: 100, height: 35), andMessage: "亮度太暗", andViewController: self)

                return

            }

            if  self.device?.torchMode != .on {

                self.session.beginConfiguration()

                try? self.device?.lockForConfiguration()

                try? self.device?.setTorchModeOn(level:0.7)

                self.device?.unlockForConfiguration()

                self.session.commitConfiguration()

            }

        }

    }

猜你喜欢

转载自blog.csdn.net/weixin_39872861/article/details/81328889