基于swift3.0
1.扫描二维码

设置扫描会话,图层和输入输出
//设置捕捉设备
let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do
{
//设置设备输入输出
let input = try AVCaptureDeviceInput(device: device)
let output = AVCaptureMetadataOutput()
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
//设置会话
let scanSession = AVCaptureSession()
scanSession.canSetSessionPreset(AVCaptureSessionPresetHigh)
if scanSession.canAddInput(input)
{
scanSession.addInput(input)
}
if scanSession.canAddOutput(output)
{
scanSession.addOutput(output)
}
//设置扫描类型(二维码和条形码)
output.metadataObjectTypes = [
AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeCode39Code,
AVMetadataObjectTypeCode128Code,
AVMetadataObjectTypeCode39Mod43Code,
AVMetadataObjectTypeEAN13Code,
AVMetadataObjectTypeEAN8Code,
AVMetadataObjectTypeCode93Code]
//预览图层
let scanPreviewLayer = AVCaptureVideoPreviewLayer(session:scanSession)
scanPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
scanPreviewLayer?.frame = view.layer.bounds
view.layer.insertSublayer(scanPreviewLayer!, at: 0)
//自动对焦
if (device?.isFocusModeSupported(.autoFocus))!
{
do { try input.device.lockForConfiguration() } catch{ }
input.device.focusMode = .autoFocus
input.device.unlockForConfiguration()
}
//设置扫描区域
NotificationCenter.default.addObserver(forName: NSNotification.Name.AVCaptureInputPortFormatDescriptionDidChange, object: nil, queue: nil, using: {[weak self] (noti) in
output.rectOfInterest = (scanPreviewLayer?.metadataOutputRectOfInterest(for: self!.scanPane.frame))!
})
//保存会话
self.scanSession = scanSession
}
catch
{
//摄像头不可用
Tool.confirm(title: "温馨提示", message: "摄像头不可用", controller: self)
return
}
开始扫描
if !scanSession.isRunning
{
scanSession.startRunning()
}
扫描结果在代理方法中
//扫描捕捉完成
extension ScanCodeViewController : AVCaptureMetadataOutputObjectsDelegate
{
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!)
{
//停止扫描
self.scanLine.layer.removeAllAnimations()
self.scanSession!.stopRunning()
//播放声音
Tool.playAlertSound(sound: "noticeMusic.caf")
//扫完完成
if metadataObjects.count > 0
{
if let resultObj = metadataObjects.first as? AVMetadataMachineReadableCodeObject
{
Tool.confirm(title: "扫描结果", message: resultObj.stringValue, controller: self,handler: { (_) in
//继续扫描
self.startScan()
})
}
}
}
}










