我已经集成了QR码扫描仪并且工作正常但是成功扫描后问题无法关闭相机。在我的代码中,如果点击确认按钮,我想关闭相机...请帮帮我谢谢!!
@objc func scanButtonTapped(sender: UIButton) {
let session = AVCaptureSession()
let captureDevice = AVCaptureDevice.default(for: .video)
do {
let input = try AVCaptureDeviceInput(device: captureDevice!)
session.addInput(input)
} catch {
self.view.makeToast("Sorry Scanner is not working!")
}
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.bounds
view.layer.addSublayer(video)
session.startRunning()
}
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if metadataObjects != nil && metadataObjects.count != 0 {
if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
if object.type == AVMetadataObject.ObjectType.qr {
let alert = UIAlertController(title: "QR Code", message: object.stringValue, preferredStyle: .alert)
alert.addAction(UIAlertAction(title:"Retake", style: .default, handler: nil))
alert.addAction(UIAlertAction(title:"Confirm", style: .default, handler: { (nil) in
self.scannedCode = object.stringValue!
}))
present(alert, animated: true, completion: nil)
}
}
}
}
答案 0 :(得分:0)
首先,您需要将会话对象保存为控制器中的实例变量。例如,
var session: AVCaptureSession?
然后在需要使用相机时实例化会话
self.session = AVCaptureSession()
然后您可以从您的metadataOutput方法引用。
self.session.stopRunning()
答案 1 :(得分:0)
将以下代码替换为确认操作:
alert.addAction(UIAlertAction(title:"Confirm", style: .default, handler: { (nil) in
self.scannedCode = object.stringValue!
self.session.stopRunning()
}