iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 30
0
Software Development

挑戰 30天內送審一支APP 系列 第 30

QR code scanner and AVCaptureSession (二) ( Final )

終於到了這一天!!
昨天已經建立了 Input Devices ,今天就要把 scan Barcode 的功能加上

  1. 首先我們要建立一個 view來當作我們的 preview 視窗 ,另外建立兩個 label 來顯示 scan 出來的資料。
var forPreview : UIView! = UIView()
var codeLabel : UILabel! = UILabel()
var typeLabel : UILabel! = UILabel()
let fullSize = UIScreen.main.bounds.size
forPreview.frame = CGRect(x: ((fullSize.width-300)/2), y: 200, width: 300 , height: 200)
forPreview.backgroundColor = UIColor.gray
codeLabel.frame = CGRect(x: ((fullSize.width-200)/2), y: 450, width: 200, height: 50)
typeLabel.frame = CGRect(x: ((fullSize.width-200)/2), y: 550, width: 200, height: 50)
codeLabel.backgroundColor = UIColor.darkGray
typeLabel.backgroundColor = UIColor.gray

...

self.view.addSubview(forPreview)
self.view.addSubview(codeLabel)
self.view.addSubview(typeLabel)
  1. 宣告”session、deviceInput、previewLayer、output”
let session :AVCaptureSession! = AVCaptureSession()
let deviceInput = DeviceInput()
let previewLayer = AVCaptureVideoPreviewLayer()
let output = AVCaptureMetadataOutput()
  1. 建立一個function,命名為 “settingPreviewLayer”來連結 Preview畫面
func settingPreviewLayer() {
previewLayer.frame = forPreview.bounds
previewLayer.session = session
previewLayer.videoGravity = .resizeAspectFill
forPreview.layer.addSublayer(previewLayer)
     }
  1. 在 < viewDidLoad >中
    “設定預覽畫面到 forpreview”
settingPreviewLayer()

將 “.backWildAngleCamera” 連結到 input

session.addInput(deviceInput.backWildAngleCamera!)

開啟 “output” ,並且設定”接受所有可辨識的meta資料”

session.addOutput(output)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.global())

開始串流

session.startRunning()
  1. 設定接收到的資料pop到 label上
 func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
for metaData in metadataObjects {
if let data = metaData as? AVMetadataMachineReadableCodeObject {
    DispatchQueue.main.async {
                    self.codeLabel.text = data.stringValue
                    self.typeLabel.text = data.type.rawValue
                }
            }
        }
    }
  1. 繼承 “AVCaptureMetadataOutputObjectsDelegate”
class ViewController: UIViewController , AVCaptureMetadataOutputObjectsDelegate{ 
  1. 這樣就可以辨識/掃描 Barcode 。
    但是有很重要的一點:
    session.addOutput(output) 必須要寫在 “output.meatadataObjectTypes” 和 “output.setMetadataObjectDelegate”前面 ,因為要將Input與 output開啟,這樣後續才知道 input資料是哪一種類型,
    如果將 session.addOutput(output) 放置在最後,則系統根本不知道輸出會是什麼資料,因此無法識別資料型態!!
  2. 大概就是這樣結束了30天的挑戰。
    special thanks : Appcamp-8th , GoodIdeas studio

上一篇
QR code scanner and AVCaptureSession (一) ( D day + 28 )
系列文
挑戰 30天內送審一支APP 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言