Environment: Xcode 4, ios 5, ipod touch 4th generation with retina display
I am trying to write a simple app that shows a video preview and capture a photo. For showing the preview, I am using the following code:
// Create the session
session = [[AVCaptureSession alloc] init];
// Set preset to the highest available
session.sessionPreset = AVCaptureSessionPresetPhoto;
// Give the frame for preview
CALayer *viewLayer = self.vPreview.layer;
NSLog(@"viewLayer = %@", viewLayer);
AVCaptureVideoPreviewLayer *captureVideoPreviewLayer =
[[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
captureVideoPreviewLayer.frame = self.vPreview.bounds;
NSLog(@"Bounds: x:%d, y:%d,height:%d,width:%d",
self.vPreview.bounds.origin.x,self.vPreview.bounds.origin.y,
self.vPreview.bounds.size.height, self.vPreview.bounds.size.width);
[self.vPreview.layer addSublayer:captureVideoPreviewLayer];
// Get AV Device
AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error = nil;
// Add Input from the above device
AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
if ( !input ) NSLog(@"ERROR: trying to open camera: %@", error);
[session addInput:input];
I have the vPreview connected to an UIView on IB story board and it occupies the full screen. However, the frame always prints as 0,0,0,0 (x,y,h,w). Can some one pls tell me what is going wrong?
There are few more lines of code that set the output and runs the session. However, by this time, the frame is already wrong. Interestingly I can see the video preview however it shows in portrait where as my app is all landscape.
Most likely this code is running in an init
method before the view has actually been loaded from the NIB file. So when you call self.vPreview.bounds
, self.vPreview
is actually nil, giving a zero CGRect return value.
With a UIViewController, the view is loaded lazily, so until something asks for the view property, the nib hasn't been loaded.
You should do your view customisation in the -viewDidLoad
method. This is called once the nib has been loaded, and all your connected IBOutlets will be non-nil.