Nazar Medeiros Nazar Medeiros - 6 months ago 54
Objective-C Question

AVFoundation change Swift code to Objective-C

I found an example code of AVFoundation which is written in Swift. I tried to change the code into Objective-C. But I am not sure if I did this correctly, because the code does not work at the moment. Could you have a look on that please?

func initialiseCaptureSession()
{
captureSession.sessionPreset = AVCaptureSessionPresetPhoto

guard let frontCamera = (AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo) as! [AVCaptureDevice])
.filter({ $0.position == .Front })
.first else
{
fatalError("Unable to access front camera")
}

do
{
let input = try AVCaptureDeviceInput(device: frontCamera)

captureSession.addInput(input)
}
catch
{
fatalError("Unable to access front camera")
}

let videoOutput = AVCaptureVideoDataOutput()

videoOutput.setSampleBufferDelegate(self, queue: dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL))
if captureSession.canAddOutput(videoOutput)
{
captureSession.addOutput(videoOutput)
}

captureSession.startRunning()
}


My Objective-C code:

-(void)initializeCaptureSession {

self.captureSession.sessionPreset = AVCaptureSessionPresetPhoto;

AVCaptureDevice *inputDevice = nil;

NSArray *devices = [AVCaptureDevice devicesWithMediaType:AVMediaTypeVideo];
AVCaptureDeviceInput *deviceInput;

for(AVCaptureDevice *camera in devices) {

if([camera position] == AVCaptureDevicePositionFront) { // is front camera
inputDevice = camera;
deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:nil];
[self.captureSession addInput:deviceInput];
break;
}
}
AVCaptureVideoDataOutput *videoOutput = nil;
[videoOutput setSampleBufferDelegate:self queue:dispatch_queue_create("sample buffer delegate", DISPATCH_QUEUE_SERIAL)];
if([self.captureSession canAddOutput:videoOutput]) {
[self.captureSession addOutput:videoOutput];
}
[self.captureSession startRunning];


}

The problem is, that in my case

if([self.captureSession canAddOutput:videoOutput]) {
[self.captureSession addOutput:videoOutput];
}


is ignored. I am not sure, but is something wrong with my self.captureSession addInput:deviceInput]; ?

Best regards,
Nazar

Answer

There is a problem with this line

AVCaptureVideoDataOutput *videoOutput = nil;

The AVCaptureVideoDataOutput is not initialised and hencecanAddOutput:videoOutput fails.

You can initialise it like this;

videoOutput = [[AVCaptureVideoDataOutput alloc] init];