我有一個使用AV Foundation的View Controller。一旦View控制器加載,用戶就能夠看到輸入設備正在看到的內容。這是因爲我已經在viewDidLoad方法實現中啓動了AVCaptureSession。嘗試使用AV Foundation捕獲靜態圖像時,出現「無效/無效連接通過」錯誤
下面是我在viewDidLoad中的代碼:
[super viewDidLoad];
AVCaptureSession *session =[[AVCaptureSession alloc]init];
[session setSessionPreset:AVCaptureSessionPresetHigh];
AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = [[NSError alloc]init];
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];
if([session canAddInput:deviceInput])
[session addInput:deviceInput];
AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc]initWithSession:session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [[self view]layer];
[rootLayer setMasksToBounds:YES];
[previewLayer setFrame:CGRectMake(0, 0, rootLayer.bounds.size.width, rootLayer.bounds.size.height/2)];
[rootLayer insertSublayer:previewLayer atIndex:0];
[session startRunning];
然後我有已被連接到一個UIButton該視圖控制器的IBAction爲方法實現。這裏是IBAction爲實現代碼:
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc]init];
AVCaptureConnection *connection = [[AVCaptureConnection alloc]init];
[stillImageOutput captureStillImageAsynchronouslyFromConnection:connection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
NSLog(@"Image Data Captured: %@", imageDataSampleBuffer);
NSLog(@"Any errors? %@", error);
if(imageDataSampleBuffer) {
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc]initWithData:imageData];
NSLog(@"%@", image);
}
}];
當我跑我的iPhone應用程序,並按下連接到該執行按鈕,我得到這個錯誤在控制檯:
*** -[AVCaptureStillImageOutput captureStillImageAsynchronouslyFromConnection:completionHandler:] - inactive/invalid connection passed.'
我看着在xcode文檔,它確實說「你只能使用addConnection將一個AVCaptureConnection實例添加到會話中:if canAddConnection:returns YES」,但我嘗試在我的AVCaptureSession對象上進行addConnection和canAddConnection方法調用,但它們甚至不顯示作爲可用選項。
我還在其他地方讀過,對於iOS,您不必手動創建連接,但這對我來說沒有意義,因爲在我的IBAction代碼中有一個方法調用:需要輸入。
因此,如果連接是自動爲您創建的,那麼它是什麼稱呼,以便我可以使用它進行輸入?
這是我第一次與AV Foundation合作,我似乎無法弄清楚這個連接錯誤。
任何幫助,非常感謝。