当我回到应用程序时,相机会被冻结(Obj-C)

时间:2016-08-27 06:42:36

标签: ios objective-c

我正在为我的应用程序制作自定义相机功能,但是当我从应用程序中退出并返回时,相机会被冻结。我该如何解决这个问题?

我想让用户再次打开应用时恢复相机,而不必关闭应用并重新打开它。

代码:

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;

        }
    }];
}

1 个答案:

答案 0 :(得分:1)

您可能正在使用viewWillAppearviewDidAppear方法在应用程序中配置相机。

使用viewDidLoad方法配置相机,只要视图控制器需要加载其视图层次结构,就会调用一次。

原因:每当应用导航回相同的viewDidAppear时,方法viewWillAppearviewController都会调用。