Search code examples
iphoneavfoundationavcapturesession

How to use AVCaptureConnnections?


I am new to AVFoundation and am trying to implement a video camera. Basically, when you click a button it will call the showCamera method. It will create the session, add audio and video inputs, and add a video output.

How do I add the AVCaptureConnection?

- (IBAction) showCamera
{
    //Add the camview to the current view ontop of controller
    [[[[[UIApplication sharedApplication] delegate] self] window] addSubview:camView];

    session = [[AVCaptureSession alloc] init];

    //Set preset on session to make recording scale high
    if ([session canSetSessionPreset:AVCaptureSessionPresetHigh]) {
        session.sessionPreset = AVCaptureSessionPresetHigh;
    }
       
    // Add inputs and outputs.
    NSArray *devices = [AVCaptureDevice devices];

    //Print out all devices on phone
    for (AVCaptureDevice *device in devices) 
    {
        
        if ([device hasMediaType:AVMediaTypeVideo]) 
        {
            
            if ([device position] == AVCaptureDevicePositionBack) 
            {
                
                //Add Rear Video input to session
                [self addRearCameraInputToSession:session withDevice:device];
                
            }
            
                        
        } 
        else if ([device hasMediaType:AVMediaTypeAudio]) 
        {
            
            //Add Microphone input to session
            [self addMicrophoneInputToSession:session withDevice:device];
        }
        else
        {
            //Show error that your camera does not have a phone
        }
    }



    //Add movie output
    [self addMovieOutputToSession:session];

    //Construct preview layer
    [self constructPreviewLayerWithSession:session onView:camView];
}

Solution

  • You don't add AVCaptureConnections manually. When you have both an input and an output added to the AVCaptureSession object, the connections are automatically created for you. Quoth the documentation:

    When an input or an output is added to a session, the session greedily forms connections between all the compatible capture inputs’ ports and capture outputs.

    Unless you need to disable one of the automatically-created connections, or change the videoMirrored or videoOrientation properties, you shouldn't have to worry about them at all.