我正在尝试创建QR阅读器。但是,当我用扫描仪打开窗口时,它崩溃并显示错误“由于未捕获的异常'NSInvalidArgumentException'而终止应用程序,原因:'***-[AVCaptureMetadataOutput setMetadataObjectTypes:]发现了不受支持的类型-使用-availableMetadataObjectTypes'”
这是我的代码:
import UIKit
import AVFoundation
import Alamofire
import SwiftyJSON
class CameraTwoViewController: UIViewController,
AVCaptureMetadataOutputObjectsDelegate {
@IBOutlet weak var square: UIImageView!
var video = AVCaptureVideoPreviewLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Creating session
let session = AVCaptureSession()
//Define capture devcie
let captureDevice = AVCaptureDevice.default(for: .video)
do
{
let input = try AVCaptureDeviceInput(device: captureDevice!)
}
catch
{
print ("ERROR")
}
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
//output.metadataObjectTypes = [AVMetadataObject.availableMetadataObjectTypes.qr]
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.bounds
view.layer.addSublayer(video)
self.view.bringSubview(toFront: square)
session.startRunning()
}
func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
if metadataObjects != nil && metadataObjects.count != 0 {
if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject {
if object.type == AVMetadataObject.ObjectType.qr {
let alert = UIAlertController(title: "Your code is:", message: object.stringValue, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Retake", style: .default, handler: nil))
alert.addAction(UIAlertAction(title: "Copy", style: .default, handler: { (nil) in
UIPasteboard.general.string = object.stringValue
}))
present(alert, animated: true, completion: nil)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
先感谢您!
最佳答案
在添加输出之前,尝试将输入添加到会话中。像这样:
func configureScanner() {
guard let captureDevice = AVCaptureDevice.default(for: .video) else {
return
}
var input: AVCaptureDeviceInput?
do {
input = try AVCaptureDeviceInput(device: captureDevice)
} catch let error {
print(error.localizedDescription)
}
guard let indeedInput = input else {
return
}
captureSession = AVCaptureSession()
captureSession!.addInput(indeedInput)
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession!.addOutput(captureMetadataOutput)
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
captureMetadataOutput.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
...
}
关于swift - 找到不受支持的类型-使用-availableMetadataObjectTypes的问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52799542/