Yomo Yomo - 3 months ago 26
Objective-C Question

Camera gets frozen when I come back to the app (Obj-C)

I'm making a custom camera function for my app, but when I go out from the app and come back, the camera is frozen. How can I fix this?

I want the camera to resume when the user opens the app again, instead of having to close the app and re-open it again.

Code:

AVCaptureSession *session;
AVCaptureStillImageOutput *stillImageOutput;

- (void)viewWillAppear:(BOOL)animated {

session = [[AVCaptureSession alloc] init];
[session setSessionPreset:AVCaptureSessionPresetPhoto];

AVCaptureDevice *inputDevice = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
NSError *error;
AVCaptureDeviceInput *deviceInput = [AVCaptureDeviceInput deviceInputWithDevice:inputDevice error:&error];

if ([session canAddInput:deviceInput]) {
[session addInput:deviceInput];
}

AVCaptureVideoPreviewLayer *previewLayer = [[AVCaptureVideoPreviewLayer alloc] initWithSession:session];
[previewLayer setVideoGravity:AVLayerVideoGravityResizeAspectFill];
CALayer *rootLayer = [[self view] layer];
[rootLayer setMasksToBounds:YES];
CGRect frame = frameForCapture.frame;

[previewLayer setFrame:frame];
[rootLayer insertSublayer:previewLayer atIndex:0];

stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
NSDictionary *outputSettings = [[NSDictionary alloc] initWithObjectsAndKeys:AVVideoCodecJPEG, AVVideoCodecKey, nil];
[stillImageOutput setOutputSettings:outputSettings];

[session addOutput:stillImageOutput];
[session startRunning];

crossButton.hidden = YES;

}

- (IBAction)takePhoto:(id)sender {

AVCaptureConnection *videoConnection = nil;

for (AVCaptureConnection *connection in stillImageOutput.connections) {

for (AVCaptureInputPort *port in [connection inputPorts]) {

if ([[port mediaType] isEqual:AVMediaTypeVideo]) {
videoConnection = connection;
crossButton.hidden = NO;
cameraButton.hidden = YES;
break;

}

}

}

[stillImageOutput captureStillImageAsynchronouslyFromConnection:videoConnection completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {

if (imageDataSampleBuffer != NULL) {

NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [UIImage imageWithData:imageData];
imageView.image = image;

}

}];

}

Answer

probably you are using viewWillAppear or viewDidAppear methods to configure your camera in your application.

use viewDidLoad method to configure camera this will called once whenever the view controller needs to load its view hierarchy.

Reason: Methods viewDidAppear and viewWillAppear called every time whenever app navigate back to the same viewController.