AVCaptureVideoDataOutputSampleBufferDelegate.CaptureOutput不叫

问题描述:

我目前有一个自行开发的框架(MySDK)和一个使用MySDK的iOS应用程序(MyApp)。AVCaptureVideoDataOutputSampleBufferDelegate.CaptureOutput不叫

在MySDK里面,我有一个MySDK中的类(扫描仪),用于处理来自设备摄像头视频输出的图像。

这里是我的代码示例:

Scanner.swift

class Scanner: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate { 

    var captureDevice : AVCaptureDevice? 
    var captureOutput : AVCaptureVideoDataOutput? 
    var previewLayer : AVCaptureVideoPreviewLayer? 
    var captureSession : AVCaptureSession? 

    var rootViewController : UIViewController? 

    func scanImage (viewController: UIViewController) 
    { 
     NSLog("%@", "scanning begins!") 

     if (captureSession == nil) { captureSession = AVCaptureSession() } 

     rootViewController = viewController; 

     captureSession!.sessionPreset = AVCaptureSessionPresetHigh 

     let devices = AVCaptureDevice.devices() 

     for device in devices { 
      if (device.hasMediaType(AVMediaTypeVideo)) { 
       if(device.position == AVCaptureDevicePosition.Back) { 
        captureDevice = device as? AVCaptureDevice 
       } 
      } 
     } 

     if (captureDevice != nil) { 
      NSLog("%@", "beginning session!") 

      beginSession() 
     } 
    } 

    func beginSession() 
    { 
     if (captureSession == nil) { captureSession = AVCaptureSession() } 
     if (captureOutput == nil) { captureOutput = AVCaptureVideoDataOutput() } 
     if (previewLayer == nil) { previewLayer = AVCaptureVideoPreviewLayer() } 

     let queue = dispatch_queue_create("myQueue", DISPATCH_QUEUE_SERIAL); 

     captureOutput!.setSampleBufferDelegate(self, queue: queue) 
     captureOutput!.videoSettings = [kCVPixelBufferPixelFormatTypeKey as NSString: Int(kCVPixelFormatType_32BGRA)] 

     captureSession!.addInput(try! AVCaptureDeviceInput(device: captureDevice)) 
     captureSession!.addOutput(captureOutput) 

     previewLayer = AVCaptureVideoPreviewLayer(session: captureSession) 
     previewLayer!.frame = rootViewController!.view.layer.frame 

     rootViewController!.view.layer.addSublayer(previewLayer!) 

     captureSession!.startRunning() 
    } 

    func captureOutput(captureOutput: AVCaptureOutput!, didOutputSampleBuffer sampleBuffer: CMSampleBufferRef!, fromConnection connection: AVCaptureConnection!) 
    { 
     NSLog("%@", "captured!") 
    } 
} 

里面MyApp的,我有一个视图控制器,它实现了IBAction,其中扫描仪类初始化,scanImage功能被触发。

MyApp.m

- (IBAction)btnScanImage_TouchDown:(id)sender 
{ 
    Scanner * scanner = [[Scanner alloc] init]; 

    [scanner scanImage:self]; 
} 

摄像机视图的应用内出现,但captureOutput功能从来没有发射,并在控制台中只包含以下两行:

2016-03-07 11:11:45.860 myapp[1236:337377] scanning begins! 
2016-03-07 11:11:45.984 myapp[1236:337377] beginning session! 

创建一个独立的应用程序,并将Scanner.swift中的代码嵌入到ViewController中可以正常工作; captureOutput函数正确触发。

有没有人有任何想法我在做什么错在这里?

经过多次试验和错误,我终于找到了解决我的问题。

很显然,我不是创造扫描仪对象作为变量,只能作为本地变量。

一旦扫描器对象被作为变量,委托方法captureOutput创建被正确地烧制。