I have integrated QR-code scanner and its working perfectly but the issue is not able to close the camera after scanned successfully. Here in my code, I want to close the camera if I tap confirm button... Please help me Thank you!!
@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)
}
}
}
}
First, you'll need to save your session object as an instance variable in your controller. For instance,
var session: AVCaptureSession?
Then instantiate your session when you need to use the camera
self.session = AVCaptureSession()
Then you can reference is from your metadataOutput method.
self.session.stopRunning()
Replace the Confirm Action by below given code :
alert.addAction(UIAlertAction(title:"Confirm", style: .default, handler: { (nil) in
self.scannedCode = object.stringValue!
self.session.stopRunning()
}
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.