美文网首页
Swift 3.0实现二维码识别

Swift 3.0实现二维码识别

作者: pankx | 来源:发表于2017-08-01 13:48 被阅读10次

    二维码现在无处不在,今天就给大家分享下在Swift下如何实现二维码识别!
    开发环境:Xcode8.2.1 iOS 10.0

    说明:本实例为纯代码编写,核心功能代码如下

    SCanViewController.swift

    import UIKit
    import AVFoundation
    
    class SCanViewController: UIViewController ,AVCaptureMetadataOutputObjectsDelegate{
    
    var setms = MessageView()
    var session: AVCaptureSession!
      override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.white
        //获取系统视频捕捉硬件设备
        let device = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo)
        do{
            //初始化视频捕设备
            let input = try AVCaptureDeviceInput(device: device)
            //初始化CaptureSessoin对象
            session = AVCaptureSession()
            //给Session添加输入设备
            session.addInput(input)
            //初始化CaptureMetadataOutput对象
            let output = AVCaptureMetadataOutput()
            //给session添加输出
            session.addOutput(output)
            //设置代理
            output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
            output.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
            
            //设置视频捕捉图层
            let preview = AVCaptureVideoPreviewLayer(session: session)
            preview?.videoGravity = AVLayerVideoGravityResizeAspectFill
            preview?.frame = view.bounds
            view.layer.addSublayer(preview!)
            //开始视频捕捉
            session.startRunning()
            
            let qrbound = UIView()
            qrbound.layer.borderWidth = 2
            qrbound.layer.borderColor = UIColor.blue.cgColor
            qrbound.frame = CGRect(x: 0, y: 0, width: 200, height: 200)
            qrbound.center = view.center
            view.addSubview(qrbound)
                   
        }catch {
            print(error)
        }
        
        
    }
    
    //省略...
    
    }
    

    项目运行图片:

    3659416-7fc9f98b66bcba00.png 3659416-2bb5e8905078c284.png 3659416-e0d1bae84207b29f.png
    源代码地址:https://github.com/pkx0128/QRCode
    注:项目需真机测试

    相关文章

      网友评论

          本文标题:Swift 3.0实现二维码识别

          本文链接:https://www.haomeiwen.com/subject/ygcszttx.html