iOS
QR-codescanner
Zoeken…
Invoering
QR-codes (Quick Response) zijn tweedimensionale barcodes die veel worden gebruikt op machineleesbare optische labels. iOS biedt een manier om de QR-codes te lezen met behulp van het AVFoundation
framework vanaf iOS 7. Dit framework biedt een set API's om de camera in te stellen / openen en QR-codes te lezen uit de camerafeed.
UIViewController scannen voor QR en video-invoer weergeven
import AVFoundation
class QRScannerViewController: UIViewController,
AVCaptureMetadataOutputObjectsDelegate {
func viewDidLoad() {
self.initCaptureSession()
}
private func initCaptureSession() {
let captureDevice = AVCaptureDevice
.defaultDevice(withMediaType: AVMediaTypeVideo)
do {
let input = try AVCaptureDeviceInput(device: captureDevice)
let captureMetadataOutput = AVCaptureMetadataOutput()
self.captureSession?.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self,
queue: DispatchQueue.main)
captureMetadataOutput
.metadataObjectTypes = [AVMetadataObjectTypeQRCode]
self.videoPreviewLayer =
AVCaptureVideoPreviewLayer(session: self.captureSession)
self.videoPreviewLayer?
.videoGravity = AVLayerVideoGravityResizeAspectFill
self.videoPreviewLayer?.frame =
self.view.layer.bounds
self._viewController?.view.layer
.addSublayer(videoPreviewLayer!)
self.captureSession?.startRunning()
} catch {
//TODO: handle input open error
}
}
private func dismissCaptureSession() {
if let running = self.captureSession?.isRunning, running {
self.captureSession?.stopRunning()
}
self.captureSession = nil
self.videoPreviewLayer?.removeFromSuperLayer()
self.videoPreviewLayer = nil
}
func captureOutput(_ captureOutput: AVCaptureOutput,
didOutputMetadataObjects metadataObjects: [Any]!,
from connection: AVCaptureConnection) {
guard metadataObjects != nil && metadataObjects.count != 0 else {
//Nothing captured
return
}
if let metadataObj =
metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
guard metadataObj.type == AVMetadataObjectTypeQRCode else {
return
}
let barCodeObject = videoPreviewLayer?
.transformedMetadataObject(for:
metadataObj as AVMetadataMachineReadableCodeObject)
as! AVMetadataMachineReadableCodeObject
if let qrValue = metadataObj.stringValue {
self.handleQRRead(value: qrValue)
}
}
}
private handleQRRead(value: String) {
//TODO: Handle the read qr
}
private captureSession: AVCaptureSession?
private videoPreviewLayer: AVCaptureVideo
}
handleQRRead
- wordt aangeroepen bij een geslaagde scan initCaptureSession
- initialiseer het scannen voor QR en camera-invoer en dismissCaptureSession
- verberg de camera-invoer en stop met scannen
QR-code scannen met AVFoudation-framework
Voorafgaand aan iOS 7, wanneer u een QR-code wilt scannen, moeten we mogelijk vertrouwen op frameworks van derden of bibliotheken zoals zBar of zXing . Maar Apple introduceerde AVCaptureMetaDataOutput
van iOS 7 voor het lezen van barcodes.
Om QR-code te lezen met behulp van AVFoundation
, moeten we AVFoundation
instellen en maken en AVCaptureSession
gebruiken captureOutput:didOutputMetadataObjects:fromConnection:
delegate-methode.
Stap 1
Importeer AVFoundation
framework en bevestig met AVCaptureMetadataOutputObjectsDelegate
protocol
import AVFoundation class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate
Stap 2
QR-codelezing is volledig gebaseerd op video-opname. Maak dus een AVCaptureSession
en stel apparaatinvoer en -uitvoer in om continue video vast te leggen. Voeg de onderstaande code toe in de viewDidLoad
methode van de viewDidLoad
// Create an instance of the AVCaptureDevice and provide the video as the media type parameter. let captureDevice = AVCaptureDevice.defaultDevice(withMediaType: AVMediaTypeVideo) do { // Create an instance of the AVCaptureDeviceInput class using the device object and intialise capture session let input = try AVCaptureDeviceInput(device: captureDevice) captureSession = AVCaptureSession() captureSession?.addInput(input) // Create a instance of AVCaptureMetadataOutput object and set it as the output device the capture session. let captureMetadataOutput = AVCaptureMetadataOutput() captureSession?.addOutput(captureMetadataOutput) // Set delegate with a default dispatch queue captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main) //set meta data object type as QR code, here we can add more then one type as well captureMetadataOutput.metadataObjectTypes = [AVMetadataObjectTypeQRCode] // Initialize the video preview layer and add it as a sublayer to the viewcontroller view's layer. videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession) videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill videoPreviewLayer?.frame = view.layer.bounds view.layer.addSublayer(videoPreviewLayer!) // Start capture session. captureSession?.startRunning() } catch { // If any error occurs, let the user know. For the example purpose just print out the error print(error) return }
Stap 3
Implementeer AVCaptureMetadataOutputObjectsDelegate
methode om de QR-code te lezen
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) { // Check if the metadataObjects array contains at least one object. If not no QR code is in our video capture if metadataObjects == nil || metadataObjects.count == 0 { // NO QR code is being detected. return } // Get the metadata object and cast it to `AVMetadataMachineReadableCodeObject` let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject if metadataObj.type == AVMetadataObjectTypeQRCode { // If the found metadata is equal to the QR code metadata then get the string value from meta data let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj) if metadataObj.stringValue != nil { // metadataObj.stringValue is our QR code } } }
hier kunnen metadata-objecten u ook de grenzen van de QR-code op de camerafeed geven. Om de grenzen te krijgen, geeft u het metadata-object eenvoudig door aan de transformedMetadataObject
methode van videoPreviewLayer
zoals hieronder.
let barCodeObject = videoPreviewLayer?.transformedMetadataObject(for: metadataObj) qrCodeFrameView?.frame = barCodeObject!.bounds