我正在使用https://www.hackingwithswift.com/example-code/media/how-to-scan-a-qr-code提供的代码来制作我自己的扫描应用程序。但我喜欢在按下按钮时进行扫描。现在为此,我将viewDidLoad()
教程中的部分放入它自己的函数中:
func cameraScanningLayer(){
view.backgroundColor = UIColor.blackColor()
captureSession = AVCaptureSession()
let videoCaptureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
let videoInput: AVCaptureDeviceInput
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch {
return
}
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
} else {
failed();
return;
}
let metadataOutput = AVCaptureMetadataOutput()
if (captureSession.canAddOutput(metadataOutput)) {
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
// need to scan barcode + QRcode
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode39Code]
} else {
failed()
return
}
// Previewlayer with camera
previewLayer = AVCaptureVideoPreviewLayer(session: captureSession);
previewLayer.frame = viewForLayer.bounds;
previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
viewForLayer.layer.addSublayer(previewLayer);
captureSession.startRunning();
}
一个按钮动作调用该函数:
func buttonScanAction() {
print("Scan")
scanEnabled = true // like to use some kind of bool/switch
self.cameraScanningLayer()
}
我遇到的问题是:
1)加载时相机不在视野中
2)按下按钮后,相机在视野中,但它总是自动扫描
所以我想到了使用全局:
var scanEnabled: Bool = false
然后,当单击按钮时,将其设置为 true 并启用扫描。
这里有一个草图供参考:
编辑 我的快速修复,这可能不是正确的方法。
我更换了
let metadataOutput = AVCaptureMetadataOutput() {...} else {
failed()
return
}
并将其放在 if 语句之间
if (scanEnabled == true) {
let metadataOutput = AVCaptureMetadataOutput()
if (captureSession.canAddOutput(metadataOutput)) {
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
// to use them both wwe need to skip AVMetadataObjectTypeQRCode
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode,AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypePDF417Code,AVMetadataObjectTypeCode128Code,AVMetadataObjectTypeCode39Code]
scanEnabled = false
} else {
failed()
return
}
}