扫描二维码可是说是很常见的需求了,利用相机扫描出二维码中的URL。主要用到的是AVFoundation框架。
首先要获取手机的相机权限,在info.plist文件中添加两个键值对Privacy - Photo Library Usage Description
与Privacy - Camera Usage Description
代码部分:
let alertAction = UIAlertController.init(title: "需要获取相机权限", message: nil, preferredStyle: .actionSheet)
alertAction.addAction(UIAlertAction.init(title: "获取相机权限", style: .default, handler: { (alertCamera) in
let picker:UIImagePickerController = UIImagePickerController()
picker.delegate = self
picker.sourceType = .camera
picker.allowsEditing = true
self.present(picker, animated: true, completion: nil)
}))
接着需要做一个扫描框:
var lineImageView: UIImageView!
var lineImage: UIImage!
var overlayView: UIView!
var ratioView: UIView!
func createView() {
lineImage = UIImage.init(named: "scanqrcode_line")
lineImageView = UIImageView.init(image: lineImage)
lineImageView.frame = CGRect(x: (UIScreen.main.bounds.size.width - 240) * 0.5, y:100 - self.lineImage.size.height * 0.5, width: 240, height: self.lineImage.size.height)
self.view.addSubview(lineImageView)
self.lineImageView.layer.zPosition = 2
self.overlayView = UIView.init(frame: CGRect(x: 0 , y: 0 ,width: self.view.frame.size.width, height: self.view.frame.size.height))
self.overlayView.alpha = 0.5
self.overlayView.backgroundColor = UIColor.black
self.view.addSubview(self.overlayView)
self.overlayView.layer.zPosition = 2
self.ratioView = UIView.init(frame: CGRect(x: (UIScreen.main.bounds.size.width - 240) * 0.5 , y: 100 ,width: 240, height: 240))
self.ratioView.layer.borderColor = UIColor.lightGray.cgColor
self.ratioView.layer.borderWidth = 1
self.view.addSubview(self.ratioView)
self.ratioView.layer.zPosition = 2
let maskLayer: CAShapeLayer! = CAShapeLayer.init()
let path: CGMutablePath! = CGMutablePath()
// left
path.addRect(CGRect(x:0,y:0,width:self.ratioView.frame.origin.x,height:self.overlayView.frame.size.height))
// right
path.addRect(CGRect(x:self.ratioView.frame.origin.x + self.ratioView.frame.size.width,y:0,width:self.overlayView.frame.size.width - self.ratioView.frame.origin.x - self.ratioView.frame.size.width,height:self.overlayView.frame.size.height))
// top
path.addRect(CGRect(x:0,y:0,width:self.overlayView.frame.size.width,height:self.ratioView.frame.origin.y))
// bottom
path.addRect(CGRect(x:0,y:self.ratioView.frame.origin.y + self.ratioView.frame.size.height,width:self.overlayView.frame.size.width,height:self.overlayView.frame.size.height - self.ratioView.frame.origin.y + self.ratioView.frame.size.height))
maskLayer.path = path
self.overlayView.layer.mask = maskLayer
let cornerImg = UIImage.init(named: "scanqrcode_corner")
let cornerImgView = UIImageView.init(image: UIImage.init(named: "scanqrcode_corner"))
cornerImgView.frame = CGRect(x:(UIScreen.main.bounds.size.width - 240) * 0.5, y:100,width: (cornerImgView.image?.size.width)!,height:(cornerImgView.image?.size.height)!)
self.view.addSubview(cornerImgView)
cornerImgView.layer.zPosition = 2
let ratateImg = UIImage.init(cgImage: (cornerImg?.cgImage)!, scale: 1, orientation: UIImageOrientation.right)
let ratateImgView = UIImageView.init(image: ratateImg)
ratateImgView.frame = CGRect(x:(UIScreen.main.bounds.size.width - 240) * 0.5 + 240 - (cornerImg?.size.width)!, y:100 , width: (cornerImg?.size.width)!, height: (cornerImg?.size.height)!)
self.view.addSubview(ratateImgView)
ratateImgView.layer.zPosition = 2
self.downAnimate()
}
func downAnimate() {
UIView.animate(withDuration: 3, animations: {
self.lineImageView.frame = CGRect(x: (UIScreen.main.bounds.size.width - 240) * 0.5, y:340 - self.lineImage.size.height * 0.5,width: 240,height: self.lineImageView.frame.size.height)
}) { (finished) in
self.upAnimate()
}
}
func upAnimate() {
UIView.animate(withDuration: 3, animations: {
self.lineImageView.frame = CGRect(x: (UIScreen.main.bounds.size.width - 240) * 0.5, y:100 - self.lineImage.size.height * 0.5,width: 240,height: self.lineImageView.frame.size.height)
}) { (finished) in
self.downAnimate()
}
}
接下来是重头戏部分,二维码扫描:
// AVCaptureSession是AVFoundation的核心类,用于捕捉视频和音频,协调视频和音频的输入和输出流
var session: AVCaptureSession!
// 视频预览层
var preview: AVCaptureVideoPreviewLayer!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.startReading()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.stopReading()
}
func startReading() {
// 获取 AVCaptureDevice 实例
let device: AVCaptureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
// 初始化输入流
let input = try AVCaptureDeviceInput.init(device: device)
// 初始化session
self.session = AVCaptureSession()
self.session.sessionPreset = AVCaptureSessionPresetHigh
// 添加输入设备到会话对象
self.session.addInput(input)
// 初始化输出流
let output: AVCaptureMetadataOutput = AVCaptureMetadataOutput.init()
self.session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
// 条码类型
output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
// 创建输出对象
self.preview = AVCaptureVideoPreviewLayer.init(session: session)
self.preview.videoGravity = AVLayerVideoGravityResizeAspectFill
self.preview.frame = CGRect(x:0,y:0,width:self.view.frame.size.width,height:self.view.frame.size.height)
self.view.layer.addSublayer(self.preview)
// 开始会话
self.session.startRunning()
}catch{
print(error)
return
}
}
func stopReading() {
self.session.startRunning()
self.session = nil
}
需要遵循AVCaptureMetadataOutputObjectsDelegate
协议,扫描结果要从代理方法中获得:
//当AVCaptureMetadataOutput对象识别QR code将触发该方法
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
// 确认是否元数据对象数组是否不为nil并至少包含一个对象,如果为nil,显示对应提示信息
if metadataObjects == nil || metadataObjects.count == 0 {
resultLabel.text = "二维码错误"
}
// 获取元数据
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
if metadataObj.type == AVMetadataObjectTypeQRCode {
print(metadataObj.stringValue)
let alertAction = UIAlertController.init(title: "\(metadataObj.stringValue!)", message: nil, preferredStyle: .alert)
self.present(alertAction, animated: true, completion: nil)
}
}
其中遇到一个问题,扫描中会出现崩溃,最终是因为添加输出流output
需要在setMetadataObjectsDelegate
之前进行,解决这个之后完美运行:
self.session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)