我在使用Xcode 9和Swift时遇到此代码的问题。它将完全构建并在我的设备上运行,正确显示摄像机输出,但实际上不会调用captureOutput来处理数据。
eimport UIKit
import AVFoundation
class ViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
var video = AVCaptureVideoPreviewLayer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
//Creating session
print("Creating Session")
let session = AVCaptureSession()
//Define capture devcie AVCaptureDeviceInput(device: captureDevice!)
print("Defining Capturing device")
let captureDevice = AVCaptureDevice.default(for: AVMediaType.video)
do
{
print("Initialzing input")
let input = try AVCaptureDeviceInput(device: captureDevice!)
session.addInput(input)
}
catch
{
print("ERROR")
}
print("Initializing output")
let output = AVCaptureMetadataOutput()
session.addOutput(output)
output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
output.metadataObjectTypes = [AVMetadataObject.ObjectType.qr]
video = AVCaptureVideoPreviewLayer(session: session)
video.frame = view.layer.bounds
view.layer.addSublayer(video)
//self.view.bringSubview(toFront: square)
session.startRunning()
}
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
print("Processing Data.")
if metadataObjects != nil && metadataObjects.count != 0
{
if let object = metadataObjects[0] as? AVMetadataMachineReadableCodeObject
{
if object.type == AVMetadataObject.ObjectType.qr
{
print("Found a pdf417.")
let alert = UIAlertController(title: "QR Scanner", 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.
}
}
在控制台中,我只是输出到打印输出("初始化输出")。这告诉我,委托没有调用captureOutput函数。我试过改变会话的范围无济于事。
有什么想法吗?