標籤:
隨著二維碼的普遍使用,二維碼掃描也成為了很多app的一個準系統,本篇主要來介紹一下如何?一個簡單的二維碼掃描功能。本文使用了XCode內建的AVFoundation
庫,利用Swfit語言實現。
實現的步驟如下:
1.擷取視頻裝置(Video)
在二維碼掃描中,我們的輸入資料流是視頻。我們需要enable視頻裝置來擷取相應的中繼資料。
2. 建立Session來處理視頻的輸入輸出資料流
3. 建立輸入輸出資料流,並添加至Session中
4. 處理二維碼資料
該方法是AVCaptureMetadataOutputObjectsDelegate的一個成員方法,我們需要實現它
~~~~~~~~~~~~~~~~~~~~~~~~~我是代碼:)~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//// ViewController.swift// QrCodeTest//// Created by XuAlvin on 2/2/16.// Copyright © 2016年 XuAlvin. All rights reserved.//import UIKitimport AVFoundationclass ViewController: UIViewController,AVCaptureMetadataOutputObjectsDelegate { var session:AVCaptureSession? override func viewDidLoad() { super.viewDidLoad() //擷取攝像裝置,注意是Video而不是Audio let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) //初始化AV Session來協調和處理AV的輸入和輸出資料流 let session = AVCaptureSession() //建立輸入資料流 let input:AVCaptureDeviceInput? = try! AVCaptureDeviceInput(device: device) if session.canAddInput(input){ session.addInput(input) } //建立輸出資料流 let output:AVCaptureMetadataOutput = AVCaptureMetadataOutput() if session.canAddOutput(output){ session.addOutput(output) //設定輸出資料流代理,從接收端收到的所有中繼資料都會被傳送到delegate方法,所有delegate方法均在queue中執行 output.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue()) //設定中繼資料的類型,這裡是二維碼QRCode output.metadataObjectTypes = [AVMetadataObjectTypeQRCode] } //建立視頻裝置拍攝視頻地區,本例中是全屏 let layer:AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer.init(session: session) layer.videoGravity = AVLayerVideoGravityResizeAspectFill layer.frame=self.view.layer.bounds self.view.layer.insertSublayer(layer, atIndex: 0) //開始採集視頻資料 session.startRunning() } //實現AVCaptureMetadataOutputObjectsDelegate的成員方法來處理二維碼資訊 func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) { session?.stopRunning() //擷取二維碼資訊中繼資料 if let metadataObjects = metadataObjects.first{ let readableObject = metadataObjects as! AVMetadataMachineReadableCodeObject //添加震動 AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) //彈出二維碼資訊 let alertCtl : UIAlertController = UIAlertController(title: "二維碼資訊", message: readableObject.stringValue, preferredStyle: UIAlertControllerStyle.Alert) //添加action到uialertcontroller,action是UIalertcontroller上的按鈕操作,建議至少添加一個,如果不添加,alertcontroller就沒有相應的按鈕退出 let alertAction : UIAlertAction = UIAlertAction(title: "Action", style: UIAlertActionStyle.Default, handler: { (param : UIAlertAction!) -> Void in print("I am alert action") }) alertCtl.addAction(alertAction) //顯示alert controller self.presentViewController(alertCtl, animated: true, completion: nil) } }}
iOS二維碼掃描的實現(Swift)