【发布时间】:2017-08-18 11:05:51
【问题描述】:
func scan(){
captureSession = AVCaptureSession()
let videoInput: AVCaptureDeviceInput
let videoCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
let metadataOutput = AVCaptureMetadataOutput()
do {
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
} catch {
return
}
if (captureSession.canAddInput(videoInput)) {
captureSession.addInput(videoInput)
} else {
failed()
return
}
if (captureSession.canAddOutput(metadataOutput)) {
captureSession.addOutput(metadataOutput)
metadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
metadataOutput.metadataObjectTypes = [AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeITF14Code, AVMetadataObjectTypeCode39Code]
} else {
failed()
return
}
var capLayer = self.previewLayer
capLayer = AVCaptureVideoPreviewLayer(session: captureSession);
capLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
capLayer?.frame = self.cameraView.layer.bounds
self.cameraView.layer.addSublayer(capLayer!)
captureSession.startRunning()
}
func failed() {
let ac = UIAlertController(title: "Scanning not supported", message: "Your device does not support scanning a code from an item. Please use a device with a camera.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
present(ac, animated: true, completion: nil)
captureSession = nil
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
captureSession.stopRunning()
if let metadataObject: AnyObject = metadataObjects.first as AnyObject? {
let readableObject = metadataObject as! AVMetadataMachineReadableCodeObject;
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
foundCode(readableObject.stringValue)
}
if (captureSession?.isRunning == true) {
captureSession.stopRunning()
captureSession = nil
}
dismiss(animated: true, completion: nil)
}
func foundCode(_ code: String) {
captureSession.stopRunning()
storeID = (UserDefaults.standard.value(forKey: DefaultsKey.storeID.rawValue) as? Int)!
scannedCode = ("\(code)")
if (captureSession?.isRunning == true) {
captureSession.stopRunning()
captureSession = nil
}
apiCall()
}
我的应用程序的结构:我在成功调用 API 后点击按钮触发扫描。一旦找到条形码,我就停止了捕获会话,但它会持续扫描并发送多个 api 调用。
建议如何在不触发的情况下停止相机扫描。
【问题讨论】:
标签: ios swift xcode swift3 barcode-scanner