首先需要: import AVFoundation
// MARK: - 1.懒加载: 会话,输入设备,输出设备,预览图层
//会话
private lazy var session: AVCaptureSession = AVCaptureSession()
//拿到输入设备
private lazy var deviceInput: AVCaptureDeviceInput? = {
//获取摄像头
let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
//创建输入对象
let input = try AVCaptureDeviceInput(device: device)
return input
} catch {
//打印错误信息
print(error)
return nil
}
}()
//拿到输出设备
private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
//创建预览图层
private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.frame = UIScreen.mainScreen().bounds
return layer
}()
//MARK: - 2.扫描二维码
func starScan() {
//先判断是否能将设备添加到回话中
if !session.canAddInput(deviceInput) {
return
}
if !session .canAddOutput(output) {
return
}
session.addInput(deviceInput)
session.addOutput(output)
//设置输入能够解析的数据类型
//设置能解析的数据类型,一定要在输出对象添加到会员之后设置
output.MetadataObjectTypes = output.availableMetadataObjectTypes
output.setMetadataObjectsDelegate(self,queue: dispatch_get_main_queue())
//添加预览图层
view.layer.insertSublayer(previewLayer,atIndex: 0)
//告诉session开始扫描
session.startRunning()
}
//MARK: - 3.实现代理 AVCaptureMetadataOutputObjectsDelegate
extension QRCodeViewController: AVCaptureMetadataOutputObjectsDelegate {
//只要解析到数据就会调用
func captureOutput(captureOutput: AVCaptureOutput!,didOutputMetadataObjects MetadataObjects: [AnyObject]!,fromConnection connection: AVCaptureConnection!) {
//获取扫描结果
//注意是: stringValue
print(MetadataObjects.last?.stringValue)
}
}