AVCaptureVideoPreviewLayer frame in Swift

avfoundation, ios, objective-c, swift

Solution

I see three points in that tutorial where you could end up not displaying the preview, and thus getting a white screen. Below are the Obj-C and Swift counterparts.

1) You might have missed adding the input to the capture session:

// [session addInput:input];
session.addInput(input)

2) You might not have initialized the preview layer's bounds to that of your view controller:

// UIView *myView = self.view;
// previewLayer.frame = myView.bounds;
previewLayer.frame = self.view.bounds

3) You might not have added the preview layer as a sublayer of your view:

// [self.view.layer addSublayer:previewLayer];
self.view.layer.addSublayer(previewLayer)

Problem

I'm trying to get the video output on my screen in Swift. But the screen stays completely white. I found this tutorial in ObjC and I followed it (only in Swift style syntax). In there there is a line `previewLayer.frame = myView.bounds;` But the field `.frame` seems to be read only in swift. And I think this might be why I don't see anything on the screen. How can I set the frame for the previewLayer in Swift?

Original source