Roi Mulia Roi Mulia - 1 year ago 65
iOS Question

AVCaptureVideoPreviewLayer (camera preview) freezes/stuck after moving to background and back

Cant figure this one out.
Everything works fine when the app is active, and than sometimes when i move the app to the background(pressing the home button) and than going back, the previewlayer freezes/stuck.
Im using viewWillAppear and viewDidAppear for the set up.
This is how i set everything up :

var backCamera = AVCaptureDevice.devicesWithMediaType(AVMediaTypeVideo)
var global_device : AVCaptureDevice!
var captureSession: AVCaptureSession?

override func viewWillAppear(animated: Bool) {

captureSession = AVCaptureSession()
captureSession!.sessionPreset = AVCaptureSessionPresetPhoto
CorrectPosition = AVCaptureDevicePosition.Back
for device in backCamera {
if device.position == AVCaptureDevicePosition.Back {
global_device = device as! AVCaptureDevice
CorrectPosition = AVCaptureDevicePosition.Back

var error: NSError?
var input = AVCaptureDeviceInput(device: global_device, error: &error)

if error == nil && captureSession!.canAddInput(input) {

stillImageOutput = AVCaptureStillImageOutput()
stillImageOutput!.outputSettings = [AVVideoCodecKey: AVVideoCodecJPEG]
if captureSession!.canAddOutput(stillImageOutput) {

previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
var bounds:CGRect = camera_Preview.layer.bounds
previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
previewLayer?.bounds = bounds
previewLayer?.position = CGPointMake(CGRectGetMidX(bounds), CGRectGetMidY(bounds))



ViewDidAppear :

var previewLayer: AVCaptureVideoPreviewLayer?

override func viewDidAppear(animated: Bool) {
previewLayer!.frame = camera_Preview.bounds

Answer Source

For future readers: this is the correct process to setting up camera inside your app.

First of all, thanks for the folks above that took their time and tried help me. They both direct me into the correct direction. Although Bill was mistaken about the viewDidLoad theory, he did gave the solution Apple Project.

This setting up camera - the correct way - is little more complicated than I thought, follow the documentation gave me excellent results. So for the Objective-C coders:

Objective C cam project

Swift cam project

About Andrea answer, he did said some great pointers you should consider when you are creating this kind of app. Check them out - they are highly relevant (most of the things he said inside the Apple project as well).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download