97 lines
2.7 KiB
Swift
97 lines
2.7 KiB
Swift
//
|
|
// CommonControllerQR.swift
|
|
// Wallet
|
|
//
|
|
// Created by Igor Danich on 03.08.2020.
|
|
// Copyright © 2020 List. All rights reserved.
|
|
//
|
|
|
|
import AVFoundation
|
|
import UIKit
|
|
|
|
class ScannerViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
|
|
|
|
private let session = AVCaptureSession()
|
|
private var previewLayer: AVCaptureVideoPreviewLayer!
|
|
|
|
var didCapture: ((String) -> Void)?
|
|
|
|
override func viewDidLoad() {
|
|
super.viewDidLoad()
|
|
|
|
view.backgroundColor = .black
|
|
|
|
guard let videoCaptureDevice = AVCaptureDevice.default(for: .video) else { return }
|
|
let videoInput: AVCaptureDeviceInput
|
|
do {
|
|
videoInput = try AVCaptureDeviceInput(device: videoCaptureDevice)
|
|
} catch {
|
|
failed()
|
|
return
|
|
}
|
|
|
|
if (session.canAddInput(videoInput)) {
|
|
session.addInput(videoInput)
|
|
} else {
|
|
failed()
|
|
return
|
|
}
|
|
|
|
let output = AVCaptureMetadataOutput()
|
|
|
|
if (session.canAddOutput(output)) {
|
|
session.addOutput(output)
|
|
output.setMetadataObjectsDelegate(self, queue: .main)
|
|
output.metadataObjectTypes = [.qr]
|
|
} else {
|
|
failed()
|
|
return
|
|
}
|
|
|
|
previewLayer = AVCaptureVideoPreviewLayer(session: session)
|
|
previewLayer.frame = view.layer.bounds
|
|
previewLayer.videoGravity = .resizeAspectFill
|
|
view.layer.addSublayer(previewLayer)
|
|
|
|
session.startRunning()
|
|
}
|
|
|
|
func failed() {
|
|
Alert.system(
|
|
title: "Scanning not supported",
|
|
text: "Your device does not support scanning a code from an item. Please use a device with a camera."
|
|
)
|
|
}
|
|
|
|
override func viewWillAppear(_ animated: Bool) {
|
|
super.viewWillAppear(animated)
|
|
if !session.isRunning {
|
|
session.startRunning()
|
|
}
|
|
}
|
|
|
|
override func viewWillDisappear(_ animated: Bool) {
|
|
super.viewWillDisappear(animated)
|
|
if session.isRunning {
|
|
session.stopRunning()
|
|
}
|
|
}
|
|
|
|
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
|
|
session.stopRunning()
|
|
guard let string = (metadataObjects.first as? AVMetadataMachineReadableCodeObject)?.stringValue else { return }
|
|
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
|
|
found(code: string)
|
|
}
|
|
|
|
func found(code: String) {
|
|
DispatchQueue.main.async {
|
|
self.didCapture?(code)
|
|
}
|
|
}
|
|
|
|
override var prefersStatusBarHidden: Bool { true }
|
|
override var supportedInterfaceOrientations: UIInterfaceOrientationMask { .portrait }
|
|
|
|
}
|